commit 112733abfe804d19aa730eaf745a7f738548f4ea Author: fengchunyu Date: Mon Nov 18 14:04:42 2024 +0800 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5eac309 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ \ No newline at end of file diff --git a/config/application.properties b/config/application.properties new file mode 100644 index 0000000..0abe42e --- /dev/null +++ b/config/application.properties @@ -0,0 +1,5 @@ +##对接汇聚中心 +#global mode +SENDTYPE=HJPT + + diff --git a/config/logback.xml b/config/logback.xml new file mode 100644 index 0000000..eaee64d --- /dev/null +++ b/config/logback.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + ${log.pattern} + + + + + + ${log.path}/info.log + + + + ${log.path}/%d{yyyy-MM-dd}.info.log + + 2 + + + ${log.pattern} + + + + INFO + + ACCEPT + + DENY + + + + + ${log.path}/error.log + + + + ${log.path}/%d{yyyy-MM-dd}.error.log + + 2 + + + ${log.pattern} + + + + ERROR + + ACCEPT + + DENY + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..37963c4 --- /dev/null +++ b/pom.xml @@ -0,0 +1,163 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.6.3 + + + com.watu + dataSend + V3 + bootdo + Demo project for Spring Boot + + 1.8 + 1.1.12 + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + + mysql + mysql-connector-java + runtime + + + + + com.alibaba + druid + ${druid.version} + + + + + + log4j + log4j + 1.2.12 + + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 2.1.1 + + + + + commons-collections + commons-collections + 3.2.1 + + + + + commons-codec + commons-codec + 1.15 + + + + + org.apache.commons + commons-lang3 + 3.6 + + + commons-configuration + commons-configuration + 1.10 + + + commons-io + commons-io + 2.5 + + + + com.alibaba + fastjson + 1.2.31 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + com.squareup.okhttp + okhttp + 2.2.0 + + + + com.squareup.okhttp3 + okhttp + 4.9.1 + + + + com.hikvision.ga + artemis-http-client + 1.1.3 + + + + org.projectlombok + lombok + true + + + + + + com.baomidou + mybatis-plus-boot-starter + 3.4.1 + + + + org.springframework.boot + spring-boot-starter-amqp + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + true + + + + + + diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..7b9cc81 --- /dev/null +++ b/readme.md @@ -0,0 +1,2 @@ +转发程序: +目前支持电信:dianxin \ No newline at end of file diff --git a/src/main/java/com/bootdo/DataSendApplication.java b/src/main/java/com/bootdo/DataSendApplication.java new file mode 100644 index 0000000..cf4f2b1 --- /dev/null +++ b/src/main/java/com/bootdo/DataSendApplication.java @@ -0,0 +1,36 @@ +package com.bootdo; + +import org.mybatis.spring.annotation.MapperScan; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@SpringBootApplication +@EnableTransactionManagement +@MapperScan("com.bootdo.datasend.*.mapper") +@EnableCaching +@EnableAsync(proxyTargetClass = true) +@EnableScheduling +public class DataSendApplication { + + private static final Logger logger = LoggerFactory.getLogger(DataSendApplication.class); + + public static void main(String[] args) { + + + SpringApplication.run(DataSendApplication.class, args); + System.out.println("ヾ(◍°∇°◍)ノ゙ bootdo启动成功 ヾ(◍°∇°◍)ノ゙\n" + + " ______ _ ______ \n" + + "|_ _ \\ / |_|_ _ `. \n" + + " | |_) | .--. .--. `| |-' | | `. \\ .--. \n" + + " | __'. / .'`\\ \\/ .'`\\ \\| | | | | |/ .'`\\ \\ \n" + + " _| |__) || \\__. || \\__. || |, _| |_.' /| \\__. | \n" + + "|_______/ '.__.' '.__.' \\__/|______.' '.__.' "); + } + +} diff --git a/src/main/java/com/bootdo/datasend/dianxin/config/RabbitConfig.java b/src/main/java/com/bootdo/datasend/dianxin/config/RabbitConfig.java new file mode 100644 index 0000000..28e768e --- /dev/null +++ b/src/main/java/com/bootdo/datasend/dianxin/config/RabbitConfig.java @@ -0,0 +1,27 @@ +package com.bootdo.datasend.dianxin.config; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.Queue; +import org.springframework.amqp.core.TopicExchange; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class RabbitConfig { + + @Bean + public Queue myQueue() { + // 创建队列 myQueue + return new Queue("myQueue", true); + } + @Bean + public TopicExchange exchange() { + return new TopicExchange("warnrecord"); + } + + @Bean + public Binding binding(Queue queue, TopicExchange exchange) { + return BindingBuilder.bind(queue).to(exchange).with("routing.key.#"); + } +} diff --git a/src/main/java/com/bootdo/datasend/dianxin/controller/standard/ApiController.java b/src/main/java/com/bootdo/datasend/dianxin/controller/standard/ApiController.java new file mode 100644 index 0000000..e62d22c --- /dev/null +++ b/src/main/java/com/bootdo/datasend/dianxin/controller/standard/ApiController.java @@ -0,0 +1,31 @@ +package com.bootdo.datasend.dianxin.controller.standard; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletResponse; + + +@Controller +@RequestMapping("/api") +@RequiredArgsConstructor +public class ApiController { + + /** + * 注册直接成功 + * + * @param str + * @param response + * @return + */ + @ResponseBody + @RequestMapping("/test") + public Object Register(@RequestBody String str, HttpServletResponse response) { + return ""; + } + + +} diff --git a/src/main/java/com/bootdo/datasend/dianxin/controller/standard/ProducerController.java b/src/main/java/com/bootdo/datasend/dianxin/controller/standard/ProducerController.java new file mode 100644 index 0000000..60442c5 --- /dev/null +++ b/src/main/java/com/bootdo/datasend/dianxin/controller/standard/ProducerController.java @@ -0,0 +1,44 @@ +package com.bootdo.datasend.dianxin.controller.standard; + +import com.alibaba.fastjson.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.PostConstruct; + +@RestController +public class ProducerController { + private static final Logger logger = LoggerFactory.getLogger(ProducerController.class); + + private final RabbitTemplate rabbitTemplate; + + public ProducerController(RabbitTemplate rabbitTemplate) { + this.rabbitTemplate = rabbitTemplate; + } + + @PostMapping("/send") + public String sendMessage(@RequestBody String message) { + rabbitTemplate.convertAndSend("warnrecord", "routing.key.warnrecord", message); + return "Message sent!"; + } + + + @PostConstruct + public String sendMessagetest() { + try { + JSONObject json = new JSONObject(); + json.put("12aaa3", "2aaa34"); + json.put("2aaa34", "45aaa6"); + rabbitTemplate.convertAndSend("warnrecord", "routing.key.warnrecord", json); + logger.info("Message sent!"); + return "Message sent!"; + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } +} diff --git a/src/main/java/com/bootdo/datasend/dianxin/domain/BaseHighThrowRecord.java b/src/main/java/com/bootdo/datasend/dianxin/domain/BaseHighThrowRecord.java new file mode 100644 index 0000000..b46f1d2 --- /dev/null +++ b/src/main/java/com/bootdo/datasend/dianxin/domain/BaseHighThrowRecord.java @@ -0,0 +1,106 @@ +package com.bootdo.datasend.dianxin.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 高抛记录表(BaseHighThrowRecord)Domain + * + * @author makejava + * @since 2024-11-18 09:34:36 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName(value = "base_high_throw_record") +public class BaseHighThrowRecord { + + /** + * 主键 + */ + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + /** + * 设备名称 + */ + private String deviceName; + + /** + * 设备编码 + */ + private String deviceCode; + + /** + * 通道国标编码 + */ + private String gbsChannelNo; + + /** + * NVR设备编号 + */ + private String serial; + + /** + * 通道号 + */ + private Integer channelNo; + + /** + * 监控大类 + */ + private Integer parentMonitoringType; + + /** + * 设备类型 + */ + private Integer deviceType; + + /** + * 设备能力集 + */ + private String structuredCameraType; + + /** + * 安装位置 + */ + private String deviceAddress; + + /** + * 设备方位 + */ + private Integer orientation; + + /** + * 设备ip + */ + private String deviceIp; + + /** + * 多维设备SN + */ + private String geminiSn; + + /** + * 场所编码 + */ + private String placeCode; + + /** + * 场所名称 + */ + private String placeName; + + /** + * 高抛图路径 + */ + private String highThrowImgurl; + + /** + * 抓拍时间 + */ + private Long passTime; + +} diff --git a/src/main/java/com/bootdo/datasend/dianxin/domain/DevopsDeviceInfo.java b/src/main/java/com/bootdo/datasend/dianxin/domain/DevopsDeviceInfo.java new file mode 100644 index 0000000..3ad7a54 --- /dev/null +++ b/src/main/java/com/bootdo/datasend/dianxin/domain/DevopsDeviceInfo.java @@ -0,0 +1,206 @@ +package com.bootdo.datasend.dianxin.domain; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.Date; + +/** + * 智能设备信息表(DevopsDeviceInfo)Domain + * + * @author makejava + * @since 2024-11-18 09:34:36 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName(value = "devops_device_info") +public class DevopsDeviceInfo { + + /** + * 主键 + */ + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + /** + * 设备名称 + */ + private String deviceName; + + /** + * 设备编码 + */ + private String deviceCode; + + /** + * 通道国标编码 + */ + private String gbsChannelNo; + + /** + * 监控大类 + */ + private Integer parentMonitoringType; + + /** + * 设备类型 + */ + private Integer deviceType; + + /** + * 设备能力集 + */ + private String structuredCameraType; + + /** + * 安装位置 + */ + private String deviceAddress; + + /** + * 设备方位 + */ + private Integer orientation; + + /** + * 设备SN编号 + */ + private String deviceSn; + + /** + * 设备品牌 + */ + private String deviceBrand; + + /** + * 设备ip + */ + private String deviceIp; + + /** + * 设备端口 + */ + private Integer devicePort; + + /** + * 设备MAC + */ + private String deviceMac; + + /** + * 设备IMEI + */ + private String deviceImei; + + /** + * 设备经度 + */ + private Double longitude; + + /** + * 设备纬度 + */ + private Double latitude; + + /** + * U3D经度 + */ + private Double u3dLongitude; + + /** + * U3D纬度 + */ + private Double u3dLatitude; + + /** + * 设备高度 + */ + private String deviceHeight; + + /** + * 设备厂家 + */ + private String manufactor; + + /** + * 设备登陆帐号 + */ + private String account; + + /** + * 设备登陆密码 + */ + private String password; + + /** + * 进出方向 + */ + private Integer direction; + + /** + * RTSP流地址 + */ + private String rtspAddress; + + /** + * 预警等级类型划分(1:一级,3:三级) + */ + private Integer isDoorwayVideo; + + /** + * 商汤region_id + */ + private String stRegionId; + + /** + * 商汤camera_idx + */ + private String stCameraIdx; + + /** + * 通道号 + */ + private Integer channelNo; + + /** + * 创建时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date createTimeV; + + /** + * 创建者 + */ + private Integer createByV; + + /** + * 更新时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date updateTimeV; + + /** + * 更新者 + */ + private Integer updateByV; + + /** + * 场所名称 + */ + private String placeName; + + /** + * 设备编号 + */ + private String serial; + + /** + * 多维设备sn + */ + private String geminiSn; + +} diff --git a/src/main/java/com/bootdo/datasend/dianxin/listener/MessageConsumer.java b/src/main/java/com/bootdo/datasend/dianxin/listener/MessageConsumer.java new file mode 100644 index 0000000..03efb93 --- /dev/null +++ b/src/main/java/com/bootdo/datasend/dianxin/listener/MessageConsumer.java @@ -0,0 +1,27 @@ +package com.bootdo.datasend.dianxin.listener; + +import com.alibaba.fastjson.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +@Component +public class MessageConsumer { + + private static final Logger logger = LoggerFactory.getLogger(MessageConsumer.class); + + //测试消费kafka + // 监听队列 "myQueue" + @RabbitListener(queues = "myQueue") + public void receiveMessage(JSONObject message) { + try { + // 处理接收到的消息 + logger.info("Received message: " + message.toString()); + // 在这里添加你对消息的处理逻辑 + } catch (Exception e) { + // 捕获并打印异常 + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/bootdo/datasend/dianxin/mapper/BaseHighThrowRecordMapper.java b/src/main/java/com/bootdo/datasend/dianxin/mapper/BaseHighThrowRecordMapper.java new file mode 100644 index 0000000..225fc65 --- /dev/null +++ b/src/main/java/com/bootdo/datasend/dianxin/mapper/BaseHighThrowRecordMapper.java @@ -0,0 +1,16 @@ +package com.bootdo.datasend.dianxin.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.bootdo.datasend.dianxin.domain.BaseHighThrowRecord; +import org.apache.ibatis.annotations.Mapper; + +/** + * 高抛记录表(BaseHighThrowRecord)Mapper + * + * @author makejava + * @since 2024-11-18 09:35:05 + */ +@Mapper +public interface BaseHighThrowRecordMapper extends BaseMapper { + +} diff --git a/src/main/java/com/bootdo/datasend/dianxin/mapper/DevopsDeviceInfoMapper.java b/src/main/java/com/bootdo/datasend/dianxin/mapper/DevopsDeviceInfoMapper.java new file mode 100644 index 0000000..9fe9c0a --- /dev/null +++ b/src/main/java/com/bootdo/datasend/dianxin/mapper/DevopsDeviceInfoMapper.java @@ -0,0 +1,16 @@ +package com.bootdo.datasend.dianxin.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.bootdo.datasend.dianxin.domain.DevopsDeviceInfo; +import org.apache.ibatis.annotations.Mapper; + +/** + * 智能设备信息表(DevopsDeviceInfo)Mapper + * + * @author makejava + * @since 2024-11-18 09:35:05 + */ +@Mapper +public interface DevopsDeviceInfoMapper extends BaseMapper { + +} diff --git a/src/main/java/com/bootdo/datasend/dianxin/service/BaseHighThrowRecordService.java b/src/main/java/com/bootdo/datasend/dianxin/service/BaseHighThrowRecordService.java new file mode 100644 index 0000000..d050d05 --- /dev/null +++ b/src/main/java/com/bootdo/datasend/dianxin/service/BaseHighThrowRecordService.java @@ -0,0 +1,17 @@ +package com.bootdo.datasend.dianxin.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.bootdo.datasend.dianxin.domain.BaseHighThrowRecord; + +import java.util.List; + +/** + * 高抛记录表(BaseHighThrowRecord)Service + * + * @author makejava + * @since 2024-11-18 09:34:35 + */ +public interface BaseHighThrowRecordService extends IService { + +} diff --git a/src/main/java/com/bootdo/datasend/dianxin/service/DevopsDeviceInfoService.java b/src/main/java/com/bootdo/datasend/dianxin/service/DevopsDeviceInfoService.java new file mode 100644 index 0000000..6f71513 --- /dev/null +++ b/src/main/java/com/bootdo/datasend/dianxin/service/DevopsDeviceInfoService.java @@ -0,0 +1,15 @@ +package com.bootdo.datasend.dianxin.service; + + +import com.baomidou.mybatisplus.extension.service.IService; +import com.bootdo.datasend.dianxin.domain.DevopsDeviceInfo; + +/** + * 智能设备信息表(DevopsDeviceInfo)Service + * + * @author makejava + * @since 2024-11-18 09:34:36 + */ +public interface DevopsDeviceInfoService extends IService { + +} diff --git a/src/main/java/com/bootdo/datasend/dianxin/service/impl/BaseHighThrowRecordServiceImpl.java b/src/main/java/com/bootdo/datasend/dianxin/service/impl/BaseHighThrowRecordServiceImpl.java new file mode 100644 index 0000000..db520a7 --- /dev/null +++ b/src/main/java/com/bootdo/datasend/dianxin/service/impl/BaseHighThrowRecordServiceImpl.java @@ -0,0 +1,18 @@ +package com.bootdo.datasend.dianxin.service.impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.bootdo.datasend.dianxin.domain.BaseHighThrowRecord; +import com.bootdo.datasend.dianxin.mapper.BaseHighThrowRecordMapper; +import com.bootdo.datasend.dianxin.service.BaseHighThrowRecordService; +import org.springframework.stereotype.Service; + +/** + * 高抛记录表(BaseHighThrowRecord)ServiceImpl + * + * @author makejava + * @since 2024-11-18 09:35:05 + */ +@Service +public class BaseHighThrowRecordServiceImpl extends ServiceImpl implements BaseHighThrowRecordService { +} diff --git a/src/main/java/com/bootdo/datasend/dianxin/service/impl/DevopsDeviceInfoServiceImpl.java b/src/main/java/com/bootdo/datasend/dianxin/service/impl/DevopsDeviceInfoServiceImpl.java new file mode 100644 index 0000000..e392168 --- /dev/null +++ b/src/main/java/com/bootdo/datasend/dianxin/service/impl/DevopsDeviceInfoServiceImpl.java @@ -0,0 +1,19 @@ +package com.bootdo.datasend.dianxin.service.impl; + + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.bootdo.datasend.dianxin.domain.DevopsDeviceInfo; +import com.bootdo.datasend.dianxin.mapper.DevopsDeviceInfoMapper; +import com.bootdo.datasend.dianxin.service.DevopsDeviceInfoService; +import org.springframework.stereotype.Service; + +/** + * 智能设备信息表(DevopsDeviceInfo)ServiceImpl + * + * @author makejava + * @since 2024-11-18 09:35:05 + */ +@Service +public class DevopsDeviceInfoServiceImpl extends ServiceImpl implements DevopsDeviceInfoService { + +} diff --git a/src/main/java/com/bootdo/schedule/ScheduleConfig.java b/src/main/java/com/bootdo/schedule/ScheduleConfig.java new file mode 100644 index 0000000..282cc23 --- /dev/null +++ b/src/main/java/com/bootdo/schedule/ScheduleConfig.java @@ -0,0 +1,18 @@ +package com.bootdo.schedule; + +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.SchedulingConfigurer; +import org.springframework.scheduling.config.ScheduledTaskRegistrar; + +import java.util.concurrent.Executors; + +@Configuration +@EnableScheduling +public class ScheduleConfig implements SchedulingConfigurer { + + @Override + public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { + taskRegistrar.setScheduler(Executors.newScheduledThreadPool(30)); + } +} diff --git a/src/main/java/com/bootdo/util/Base64Util.java b/src/main/java/com/bootdo/util/Base64Util.java new file mode 100644 index 0000000..99f94ae --- /dev/null +++ b/src/main/java/com/bootdo/util/Base64Util.java @@ -0,0 +1,76 @@ +package com.bootdo.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.imageio.ImageIO; +import javax.xml.bind.DatatypeConverter; +import java.awt.image.BufferedImage; +import java.io.*; +import java.net.URLEncoder; + +public class Base64Util { + private static final Logger logger = LoggerFactory.getLogger(Base64Util.class); + + /** + * base64转图片 + * + * @param base64Code base64码 + */ + public static void convertBase64ToImage(String base64Code, String picname) { + + BufferedImage image = null; + byte[] imageByte = null; + try { + imageByte = DatatypeConverter.parseBase64Binary(base64Code); + ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); + image = ImageIO.read(new ByteArrayInputStream(imageByte)); + bis.close(); + File outputfile = new File("d:\\" + picname); + ImageIO.write(image, "jpg", outputfile); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 将图片转换成Base64编码 + * + * @param imgFile 待处理图片 + * @return + */ + public static String getImgStr(String imgFile) { + //将图片文件转化为字节数组字符串,并对其进行Base64编码处理 + InputStream in = null; + byte[] data = null; + //读取图片字节数组 + try { + in = new FileInputStream(imgFile); + data = new byte[in.available()]; + in.read(data); + in.close(); + } catch (Exception e) { + logger.info("base64转换异常,url:" + imgFile); + return ""; + } + return java.util.Base64.getEncoder().encodeToString(data); + } + + + /** + * 处理base64串 将+变成空格 + * + * @param urlBase64 + * @return + */ + public static String encodeStr(String urlBase64) { + try { + urlBase64 = URLEncoder.encode(urlBase64, "UTF-8"); + } catch (Exception e) { + logger.info(StringKit.getTrace(e)); + } + return urlBase64; + } + + +} diff --git a/src/main/java/com/bootdo/util/ConfigParam.java b/src/main/java/com/bootdo/util/ConfigParam.java new file mode 100644 index 0000000..cfc1e70 --- /dev/null +++ b/src/main/java/com/bootdo/util/ConfigParam.java @@ -0,0 +1,10 @@ +package com.bootdo.util; + +import org.springframework.stereotype.Component; + +@Component +public class ConfigParam { + + + public static String SENDTYPE = PropertiesUtil.queryPropertiesByKey("SENDTYPE"); +} diff --git a/src/main/java/com/bootdo/util/DateTool.java b/src/main/java/com/bootdo/util/DateTool.java new file mode 100644 index 0000000..1c47f4b --- /dev/null +++ b/src/main/java/com/bootdo/util/DateTool.java @@ -0,0 +1,662 @@ +package com.bootdo.util; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +/** + * 时间小工具 + */ +@Component +public class DateTool { + private static final Logger logger = LoggerFactory.getLogger(DateTool.class); + + private static final long SECOND = 24 * 60 * 60 * 1000L; + private static final SimpleDateFormat ym = new SimpleDateFormat("yyyyMM"); + private static final SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + private static final SimpleDateFormat ymdhms = new SimpleDateFormat("yyyyMMddHHmmss"); + private static final SimpleDateFormat yyyy = new SimpleDateFormat("yyyy"); + private static final SimpleDateFormat yMMdd = new SimpleDateFormat("MM-dd"); + private static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd"); + private static final SimpleDateFormat HHmmss = new SimpleDateFormat("HH:mm:ss"); + private static final SimpleDateFormat YYYYMMDD = new SimpleDateFormat("yyyy-MM-dd"); + + public static final SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); + public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + private static final SimpleDateFormat ymdDir = new SimpleDateFormat("yyyyMMdd"); + + + /** + * 年 + * 2022 + */ + public int getYear(Date date) { + int rel = 0; + if (null == date) { + return 0; + } + try { + rel = Integer.parseInt(yyyy.format(date)); + } catch (Exception e) { + return rel; + } + return rel; + } + + /** + * 年月 + * 202205 + */ + public String yearMonth() { + return ym.format(new Date()); + } + + /** + * 当日开始时间 + */ + public String getStartTime() { + long current = System.currentTimeMillis();//当前时间毫秒数 + //今天零点零分零秒的毫秒数 + long zero = ((current / SECOND) * SECOND - TimeZone.getDefault().getRawOffset()); + return ymd.format(zero); + } + + /** + * 带T时间处理 + * + * @param time + * @return + */ + public String getDateTimeT(long time) { + String ymd = YYYYMMDD.format(new Date(time * 1000)); + String hms = HHmmss.format(new Date(time * 1000)); + return (ymd + "T" + hms); + } + + /** + * 今日0点的绝对秒 + */ + public Long getStartTimeLong() { + long current = System.currentTimeMillis();//当前时间毫秒数 + //今天零点零分零秒的毫秒数 + long zero = ((current / SECOND) * SECOND - TimeZone.getDefault().getRawOffset()); + return zero / 1000; + } + + /** + * 当日结束时间 + */ + public String getEndTime() { + long current = System.currentTimeMillis();//当前时间毫秒数 + //今天零点零分零秒的毫秒数 + long zero = (current / SECOND) * SECOND - TimeZone.getDefault().getRawOffset(); + //今天23点59分59秒的毫秒数 + long twelve = (zero + SECOND - 1); + return ymd.format(twelve); + } + + /** + * 今天23点59分59秒 绝对秒 + */ + public Long getEndTimeLong() { + long current = System.currentTimeMillis();//当前时间毫秒数 + //今天零点零分零秒的毫秒数 + long zero = (current / SECOND) * SECOND - TimeZone.getDefault().getRawOffset(); + //今天23点59分59秒的毫秒数 + long twelve = (zero + SECOND - 1); + return twelve / 1000; + } + + /** + * 获取日期格式字符串时间 + */ + public String getDateTime(long time) { + if (time == 0L) { + return ""; + } + String format = ymd.format(new Date(time * 1000)); + if (StringUtils.isNotBlank(format)) { + return format; + } else { + return ""; + } + } + + /** + * 今天 2022-08-18 00:00:00 + */ + public String getDayStart() { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + String startDate = ymd.format(calendar.getTime()); + startDate = startDate.substring(0, 10) + " 00:00:00"; + return startDate; + } + + /** + * 今天 2022-08-18 23:59:59 + */ + public String getDayEnd() { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + String endDate = ymd.format(calendar.getTime()); + endDate = endDate.substring(0, 10) + " 23:59:59"; + return endDate; + } + + /** + * 获取前一天 2022-08-15 00:00:00 + */ + public static String getLastDayStart() { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DAY_OF_MONTH, -1); + String startDate = ymd.format(calendar.getTime()); + startDate = startDate.substring(0, 10) + " 00:00:00"; + return startDate; + } + + /** + * 获取前一天 时间戳 + */ + public static String getLastDayStartTimestamp() { + try { + String format = "yyyy-MM-dd HH:mm:ss"; + String dateStr = getLastDayStart(); + SimpleDateFormat ft = new SimpleDateFormat(format); + Date date = ft.parse(dateStr); + long resL = date.getTime(); + String res = StringKit.toString(resL / 1000); + return StringKit.toString(res); + } catch (Exception e) { + return ""; + } + } + + /** + * 获取前一天 2022-08-15 23:59:59 + */ + public String getLastDayEnd() { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DAY_OF_MONTH, -1); + String endDate = ymd.format(calendar.getTime()); + endDate = endDate.substring(0, 10) + " 23:59:59"; + return endDate; + } + + /** + * 获取前一天 年月日 + */ + public String getDayStr() { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DAY_OF_MONTH, -1); + String dayStr = yyyyMMdd.format(calendar.getTime()); + return dayStr; + } + + /** + * 获取年月日时间 + * yyyyMMdd + */ + public String getDayStr(long longStr) { + String rel = ""; + try { + rel = yyyyMMdd.format(longStr * 1000); + } catch (Exception e) { + + } + return rel; + } + + /** + * 获取年月日时间 + * yyyyMMdd + */ + public String getDayStr2(String date) { + String rel = ""; + try { + rel = yyyyMMdd.format(ymd.parse(date)); + } catch (Exception e) { + + } + return rel; + } + + /** + * 日期字符串 计算 绝对秒 + */ + public long getDayLong(String date) { + try { + Date parse = ymd.parse(date); + return parse.getTime() / 1000; + } catch (ParseException e) { + e.printStackTrace(); + } + return 0L; + } + + /** + * 获取当前年份 + */ + public String getYear() { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DAY_OF_MONTH, -1); + String endDate = ymd.format(calendar.getTime()); + endDate = endDate.substring(0, 10) + " 23:59:59"; + return endDate; + } + + /** + * 获取每个月的第一天 + */ + public String getMonthFirst() { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.DATE, 1); + calendar.roll(Calendar.DATE, -1); + + SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy-MM-"); + String startTime = sdfTwo.format(new Date()) + "01 00:00:00"; + return startTime; + } + + /** + * 获取每个月的最后一天 + */ + public String getMonthLast() { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.DATE, 1); + calendar.roll(Calendar.DATE, -1); + + int maxDate = calendar.get(Calendar.DATE); + SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy-MM-"); + String endTime = sdfTwo.format(new Date()) + maxDate + " 23:59:59"; + return endTime; + } + + + /** + * 获取前n天 2022-08-15 23:59:59 + */ + public String getDayStart(int n) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DAY_OF_MONTH, -n); + String startDate = ymd.format(calendar.getTime()); + startDate = startDate.substring(0, 10) + " 00:00:00"; + return startDate; + } + + /** + * 获取前n天 2022-08-15 23:59:59 + */ + public String getDayStartYYYYMMDD(int n) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DAY_OF_MONTH, -n); + String startDate = ymd.format(calendar.getTime()); + startDate = startDate.substring(0, 10); + return startDate; + } + + /** + * 获取前n天 2022-08-15 23:59:59 + */ + public String getDayEnd(int n) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DAY_OF_MONTH, -n); + String endDate = ymd.format(calendar.getTime()); + endDate = endDate.substring(0, 10) + " 23:59:59"; + return endDate; + } + + /** + * 获取n天前的指定日期 + */ + public String getYMD(int n) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DAY_OF_MONTH, -n); + String ymd = yyyyMMdd.format(calendar.getTime()); + return ymd; + } + + /** + * 获取当前ymdhms日期格式 + */ + public String getYmdhms() { + return ymdhms.format(new Date()); + } + + /** + * yyyyMMdd转mm.dd + */ + public String timeConversion(String yyyyMMdd) { + String rel = ""; + try { + if (StringUtils.isBlank(yyyyMMdd)) { + return rel; + } + if (yyyyMMdd.length() != 8) { + return rel; + } + String mm = yyyyMMdd.substring(4, 6); + String dd = yyyyMMdd.substring(6, 8); + rel = String.valueOf(Integer.parseInt(mm)) + "." + String.valueOf(Integer.parseInt(dd)); + } catch (Exception e) { + + } + return rel; + } + + /** + * 年月 + * m=0表示当月 + * m=1表示前一月 + * m=2表示前两月 + */ + public String yearMonth(int m) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.MONTH, -m); + return ym.format(calendar.getTime()); + } + + public String getDayStr3(String date) { + String rel = ""; + try { + Date parse = yyyyMMdd.parse(date); + } catch (ParseException e) { + + } + return rel; + } + + public long daysBetween(String one, String two) { + long difference = 0L; + try { + Date parseOne = yyyyMMdd.parse(one); + Date parseTwo = yyyyMMdd.parse(two); + difference = (parseOne.getTime() - parseTwo.getTime()) / 86400000; + } catch (ParseException e) { + e.printStackTrace(); + } + return Math.abs(difference) + 1; + } + + + /** + * 获取前N天 MMdd + */ + public static String getLastDayMmdd(int num) { + if (num == 0) { + num = 1; + } + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DAY_OF_MONTH, -num); + String startDate = yMMdd.format(calendar.getTime()); + return startDate; + } + + /** + * n个月前的1号开始时间 + */ + public String getMonthFirst(int n) { + SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy-MM"); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.MONTH, -n); + Date m = calendar.getTime(); + String format = sdfTwo.format(m); + return format + "-01 00:00:00"; + } + + /** + * n个月前的最后一天结束时间 + */ + public String getMonthLast(int n) { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.MONTH, 1 - n + 2); + calendar.set(Calendar.DATE, 1); + calendar.roll(Calendar.DATE, -1); + int maxDate = calendar.get(Calendar.DATE); + SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy-MM-"); + String endTime = sdfTwo.format(calendar.getTime()) + maxDate + " 23:59:59"; + return endTime; + } + + + /** + * 时间转换为时间戳 + */ + public static String dateToStamp(String s) { + + try { + String res; + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); + Date date = simpleDateFormat.parse(s); + long ts = date.getTime(); + ts = ts / 1000; + res = StringKit.toString(ts); + return res; + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 时间转换为时间戳 + */ + public static String getNowTimeStr() { + + try { + String currentTime = df.format(new Date()); + return currentTime; + } catch (Exception e) { + logger.info(StringKit.getTrace(e)); + e.printStackTrace(); + } + return ""; + } + + public static String getTime() { + return ymdhms.format(new Date()); + } + + + /** + * 时间戳转换成 标准时间 + * + * @param seconds + * @param format + * @return + */ + public static String timeStamp2Date(String seconds, String format) { + if (seconds == null || seconds.isEmpty() || seconds.equals("null")) { + return ""; + } + if (format == null || format.isEmpty()) { + format = "yyyy-MM-dd HH:mm:ss"; + } + SimpleDateFormat sdf = new SimpleDateFormat(format); + return sdf.format(new Date(Long.valueOf(seconds + "000"))); + } + + /** + * 上个月 时间戳转换成 标准时间 + * + * @param format + * @return + */ + public static String getLastMonth(String format) { + Calendar calendar = Calendar.getInstance();//日历对象 + calendar.setTime(new Date());//设置当前日期 + calendar.add(Calendar.MONTH, -1);//月份减一 + Date lastMonth = calendar.getTime(); + + if (format == null || format.isEmpty()) { + format = "yyyy-MM-dd HH:mm:ss"; + } + SimpleDateFormat sdf = new SimpleDateFormat(format); + return sdf.format(lastMonth); + } + + public static String getDateStr(String sendTime) { + String dateStr; + String dateFir = StringKit.toString(sendTime); + Date date = null; + if ("".equals(dateFir)) { + date = new Date(System.currentTimeMillis()); + } else { + Long dateFirL = Long.valueOf(dateFir); + date = new Date(dateFirL * 1000); + } + dateStr = sdf.format(date); + return dateStr; + } + + public static String convertTimeToString(String longTime) { + String format = "yyyyMMddHHmmss"; + try { + Timestamp t = new Timestamp(Long.parseLong(longTime) * 1000L); + SimpleDateFormat sDateFormat = new SimpleDateFormat(format); + return sDateFormat.format(t); + } catch (Exception ex) { + throw new RuntimeException((new StringBuilder()).append("Can't format the time by format[").append(format).append("]!").toString()); + } + } + + /** + * 30天前 + * + * @return + */ + public static String readRecordStart() { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DAY_OF_MONTH, -30); + String startDate = sdf.format(calendar.getTime()); + startDate = startDate.substring(0, 10) + " 00:00:00"; + return startDate; + } + + public static String readRecordDayStart() { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DAY_OF_MONTH, 0); + String startDate = sdf.format(calendar.getTime()); + startDate = startDate.substring(0, 10) + " 00:00:00"; + return startDate; + } + + /** + * 今天 + * + * @return + */ + public static String readRecordEnd() { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + String endDate = sdf.format(calendar.getTime()); + endDate = endDate.substring(0, 10) + " 23:59:59"; + return endDate; + } + + /** + * 根据绝对秒 计算年月 yyyyMM + * + * @param tempLongTime + * @return + */ + public static int yearMonth(String tempLongTime) { + if (StringUtils.isBlank(tempLongTime) || tempLongTime.length() != 10) { + return 0; + } + String format = ym.format(new Date(Long.parseLong(tempLongTime) * 1000L)); + return Integer.parseInt(format); + } + + public static String yearMonthDay(String tempLongTime) { + if (StringUtils.isBlank(tempLongTime) || tempLongTime.length() != 10) { + return null; + } + String format = ymd.format(new Date(Long.parseLong(tempLongTime) * 1000L)); + return format; + } + + + /** + * 特殊场景 + * 通过jpg获取时间 + * + * @param tempLongTime + * @return + */ + public static long ymdhms(String tempLongTime) { + long rel = 0; + try { + rel = ymdhms.parse(tempLongTime).getTime() / 1000; + } catch (ParseException e) { + e.printStackTrace(); + } + return rel; + } + + public static long getLongTime(String tempLongTime) { + long rel = 0; + try { + rel = ymd.parse(tempLongTime).getTime() / 1000; + } catch (ParseException e) { + e.printStackTrace(); + } + return rel; + } + + public static String ymdhmsDate() { + return ymdhms.format(new Date()); + } + + /** + * 开始时间 + * + * @return + */ + public String getStart() { + long time = System.currentTimeMillis() / 1000 - 60 * 60 * 24 * 180; + return ymd.format(new Date(time * 1000)); + } + + /** + * 当前日期 + * + * @return + */ + public String getEnd() { + long time = System.currentTimeMillis(); + return ymd.format(new Date(time)); + } + + + /** + * 时间戳对应日期目录 + */ + public static String dateDir(long longTime) { + String tempLongTime = String.valueOf(longTime); + String format = ymdDir.format(new Date(Long.parseLong(tempLongTime) * 1000L)); + return format; + } + +} diff --git a/src/main/java/com/bootdo/util/DateUtils.java b/src/main/java/com/bootdo/util/DateUtils.java new file mode 100644 index 0000000..9a76c12 --- /dev/null +++ b/src/main/java/com/bootdo/util/DateUtils.java @@ -0,0 +1,96 @@ +package com.bootdo.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 日期处理 + */ +public class DateUtils { + private final static Logger logger = LoggerFactory.getLogger(DateUtils.class); + /** + * 时间格式(yyyy-MM-dd) + */ + public final static String DATE_PATTERN = "yyyy-MM-dd"; + /** + * 时间格式(yyyy-MM-dd HH:mm:ss) + */ + public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; + + public static String format(Date date) { + return format(date, DATE_PATTERN); + } + + public static String format(Date date, String pattern) { + if (date != null) { + SimpleDateFormat df = new SimpleDateFormat(pattern); + return df.format(date); + } + return null; + } + + /** + * 计算距离现在多久,非精确 + * + * @param date + * @return + */ + public static String getTimeBefore(Date date) { + Date now = new Date(); + long l = now.getTime() - date.getTime(); + long day = l / (24 * 60 * 60 * 1000); + long hour = (l / (60 * 60 * 1000) - day * 24); + long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60); + long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); + String r = ""; + if (day > 0) { + r += day + "天"; + } else if (hour > 0) { + r += hour + "小时"; + } else if (min > 0) { + r += min + "分"; + } else if (s > 0) { + r += s + "秒"; + } + r += "前"; + return r; + } + + /** + * 计算距离现在多久,精确 + * + * @param date + * @return + */ + public static String getTimeBeforeAccurate(Date date) { + Date now = new Date(); + long l = now.getTime() - date.getTime(); + long day = l / (24 * 60 * 60 * 1000); + long hour = (l / (60 * 60 * 1000) - day * 24); + long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60); + long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); + String r = ""; + if (day > 0) { + r += day + "天"; + } + if (hour > 0) { + r += hour + "小时"; + } + if (min > 0) { + r += min + "分"; + } + if (s > 0) { + r += s + "秒"; + } + r += "前"; + return r; + } + + public static String getDateStr(String seconds){ + SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_PATTERN); + return sdf.format(new Date(Long.valueOf(seconds+"000"))); + } +} diff --git a/src/main/java/com/bootdo/util/EncryptUtil.java b/src/main/java/com/bootdo/util/EncryptUtil.java new file mode 100644 index 0000000..e22ff26 --- /dev/null +++ b/src/main/java/com/bootdo/util/EncryptUtil.java @@ -0,0 +1,119 @@ +package com.bootdo.util; + +import org.apache.commons.codec.binary.Base64; + +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.Charset; +import java.util.Arrays; + +/** + * ant 加密 工具类 + * + * @author bc + * @Date 2020-08-12 9:34 + */ +public class EncryptUtil { + + protected final static Charset CHARSET_UTF8 = Charset.forName("utf-8"); + + private final static String SECRET_ID = "SecretId"; + + private final static String BODY = "Body"; + + private final static String TIME_STAMP = "Timestamp"; + + private final static String SIGNVERSION = "Signversion"; + + private final static String MAC_NAME = "HmacSHA1"; + + private final static String EQUALS_SYMBOL = "="; + + private final static String AND = "&"; + + private final static Base64 base64 = new Base64(); + + /** + * 生成签名 + * + * @param timestamp 时间戳 + * @param secretId 申请的secretId + * @param secretKey 申请的secretKey + * @param contentJsonString 待加密的字符串 + * @param method 方法名 + * @return 生成的验签签名 + */ + public static String signature(String timestamp, String secretId, String secretKey, String contentJsonString,String method) throws Exception { + + String stringBuilder = toSignSourceSimplePost(timestamp, secretId, contentJsonString); + System.out.println("stringBuilder:"+stringBuilder); + byte[] bytes = hmacSHA1Encrypt(stringBuilder, secretKey); + return base64.encodeToString(bytes); + } + + /** + * 简单拼接顺序字符串 + */ + private static String toSignSourceSimplePost(String timestamp, String secretId, String jsonStr) { + StringBuilder builder = new StringBuilder(); + builder.append(SECRET_ID).append(EQUALS_SYMBOL).append(secretId).append(AND); + builder.append(TIME_STAMP).append(EQUALS_SYMBOL).append(timestamp).append(AND); + builder.append(SIGNVERSION).append(EQUALS_SYMBOL).append("v2").append(AND); + builder.append(BODY).append(EQUALS_SYMBOL).append(jsonStr); + return builder.toString(); + } + + private static String toSignSourceSimpleGet(String timestamp, String secretId, String jsonStr) { + StringBuilder builder = new StringBuilder(); + builder.append(SECRET_ID).append(EQUALS_SYMBOL).append(secretId).append(AND); + builder.append(TIME_STAMP).append(EQUALS_SYMBOL).append(timestamp).append(AND); + builder.append(SIGNVERSION).append(EQUALS_SYMBOL).append("v2"); + return builder.toString(); + } + + /** + * 加密原始参数 + * + * @param encryptText 待加密的原始字符串 + * @param encryptKey 颁发的secretKey + * @return 加密的byte数组,用于生成签名 + */ + private static byte[] hmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception { + //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称 + SecretKey secretKey = new SecretKeySpec(encryptKey.getBytes(CHARSET_UTF8), MAC_NAME); + //生成一个指定 Mac 算法 的 Mac 对象 + Mac mac = Mac.getInstance(MAC_NAME); + //用给定密钥初始化 Mac 对象 + mac.init(secretKey); + + byte[] data = encryptText.getBytes(CHARSET_UTF8); + if (null == data || 0 == data.length){ + return data; + } + if(data.length>1024){ + data = Arrays.copyOfRange(data,0,1024); + } + + //完成 Mac 操作 + return mac.doFinal(data); + } + + private static String key = "SecretId=J5HrA2KccOexV0IWx8I&Timestamp=1597659585761&Body={\n" + + " \"account\": \"string\",\n" + + " \"cameraId\": \"string\",\n" + + " \"cameraName\": \"string\",\n" + + " \"cameraSerialNum\": \"string\",\n" + + " \"deviceType\": \"string\",\n" + + " \"groupId\": \"string\",\n" + + " \"ip\": \"string\",\n" + + " \"lat\": \"string\",\n" + + " \"lng\": \"string\",\n" + + " \"password\": \"string\",\n" + + " \"port\": \"string\",\n" + + " \"rtsp\": \"string\",\n" + + " \"suppleRtsp\": \"string\"\n" + + "}"; + + +} diff --git a/src/main/java/com/bootdo/util/Gl.java b/src/main/java/com/bootdo/util/Gl.java new file mode 100644 index 0000000..728d247 --- /dev/null +++ b/src/main/java/com/bootdo/util/Gl.java @@ -0,0 +1,56 @@ +package com.bootdo.util; + +/** + * 全局常量类 + */ +public class Gl { + + public static final String DEFAULT_20 = "88321023198905233412"; + public static final int BATCH_NUM = 1000; + + + // bcp文件基础路径 + public static final String BASE_BCP_PATH = "/home/dataaccess/"; + // bcp文件error路径 + public static final String BASE_BCP_PATH_ERROR = "/home/error/"; + // bcp类型 人脸 + public static final String BCP_TYPE_RENLIAN = "renlian"; + // bcp类型 车辆 + public static final String BCP_TYPE_CHELIANG = "cheliang"; + // bcp类型 门禁 + public static final String BCP_TYPE_MENJING = "menjing"; + // bcp类型 测温 + public static final String BCP_TYPE_CEWEN = "cewen"; + // bcp类型 ETC + public static final String BCP_TYPE_ETC = "etc"; + // bcp类型 高空抛物 + public static final String BCP_TYPE_GAOPAO = "gaopao"; + // bcp类型 高空抛物 + public static final String BCP_TYPE_YANGAN = "yangan"; + + // bcp文件标识 人脸抓拍 + public static final String FILE_FLAG_FACE = "FaceCapture"; + // bcp文件标识 人脸门禁 + public static final String FILE_FLAG_DOOR_FACE = "DoorEvent"; + // bcp文件标识 测温 + public static final String FILE_FLAG_THERMAL = "Thermal"; + // bcp文件标识 车辆抓拍 + public static final String FILE_FLAG_VEHICLE = "CarMessage"; + // bcp文件标识 ETC抓拍 + public static final String FILE_FLAG_ETC = "ETC"; + // bcp文件标识 高空抛物 + public static final String FILE_FLAG_GAOPAO = "Parabolic"; + // bcp文件标识 烟感告警 + public static final String FILE_FLAG_YANGAN = "Smoke_"; + // bcp文件标识 烟感状态 + public static final String FILE_FLAG_YANGAN_STATUS = "SmokeStatus"; + + // txt文件标识 多码 电子围栏 + public static final String FILE_FLAG_FENCE = "WY_"; + + // bcp文件标识 + public static final String FILE_FLAG_BCP = ".bcp"; + // txt文件标识 + public static final String FILE_FLAG_TXT = ".txt"; + +} diff --git a/src/main/java/com/bootdo/util/Md5Utils.java b/src/main/java/com/bootdo/util/Md5Utils.java new file mode 100644 index 0000000..0524bd4 --- /dev/null +++ b/src/main/java/com/bootdo/util/Md5Utils.java @@ -0,0 +1,106 @@ +package com.bootdo.util; + +import java.security.MessageDigest; + +/** + * + * MD5加密工具(是基于hash算法实现,不可逆) + * + * @author xuyi3 + * @2016年7月13日 @下午3:10:54 + * @Md5Utils + * @功能说明:
+ * @春风十里不如你 + * @备注 + */ +public class Md5Utils { + + /** 16进制的字符数组 */ + private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", + "e", "f" }; + + /** + * + * + * @param source + * 需要加密的原字符串 + * @param encoding + * 指定编码类型 + * @param uppercase + * 是否转为大写字符串 + * @return + */ + public static String MD5Encode(String source, String encoding, boolean uppercase) { + String result = null; + try { + result = source; + // 获得MD5摘要对象 + MessageDigest messageDigest = MessageDigest.getInstance("MD5"); + // 使用指定的字节数组更新摘要信息 + messageDigest.update(result.getBytes(encoding)); + // messageDigest.digest()获得16位长度 + result = byteArrayToHexString(messageDigest.digest()); + + } catch (Exception e) { + e.printStackTrace(); + } + return uppercase ? result.toUpperCase() : result; + } + + /** + * 转换字节数组为16进制字符串 + * + * @param bytes + * 字节数组 + * @return + */ + private static String byteArrayToHexString(byte[] bytes) { + StringBuilder stringBuilder = new StringBuilder(); + for (byte tem : bytes) { + stringBuilder.append(byteToHexString(tem)); + } + return stringBuilder.toString(); + } + + /** + * 转换byte到16进制 + * + * @param b + * 要转换的byte + * @return 16进制对应的字符 + */ + private static String byteToHexString(byte b) { + int n = b; + if (n < 0) { + n = 256 + n; + } + int d1 = n / 16; + int d2 = n % 16; + return hexDigits[d1] + hexDigits[d2]; + } + + + public static String getResponse(String username, String realm, String password, String method, String url, String nonce, String nc, String cnonce, String qop) { + // HA1 = md5("username:realm:password"); + String Ha1str = username+":"+realm+":"+password; + String resHa1 = MD5Encode(Ha1str,"utf-8",false); + +// HA2 = md5("method:uri"); + String Ha2str = method+":"+url; + String resHa2 = MD5Encode(Ha2str,"utf-8",false); + + +// response = md5("HA1:nouce:nc:cnonce:qop:HA2"); + String responsestr = resHa1+":"+nonce+":"+nc+":"+cnonce+":"+qop+":"+resHa2; + String responseHa2 = MD5Encode(responsestr,"utf-8",false); +// 188ffa2b22cb3b0cf20d5c05131953fe + return responseHa2; + } + + +} + + + + +//备注:其实apache commones Codec包中有常用的一些加密算法实现 diff --git a/src/main/java/com/bootdo/util/MySSLSocketClient.java b/src/main/java/com/bootdo/util/MySSLSocketClient.java new file mode 100644 index 0000000..878ccb6 --- /dev/null +++ b/src/main/java/com/bootdo/util/MySSLSocketClient.java @@ -0,0 +1,78 @@ +package com.bootdo.util; + +import java.net.Socket; +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509ExtendedTrustManager; + +public class MySSLSocketClient { + + //获取TrustManager + public static X509ExtendedTrustManager X509 = new X509ExtendedTrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException { + + } + + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException { + + } + + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException { + + } + + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException { + + } + + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + + } + + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + }; + + //获取这个SSLSocketFactory + public static SSLSocketFactory getSSLSocketFactory() { + try { + SSLContext sslContext = SSLContext.getInstance("SSL"); + sslContext.init(null, new TrustManager[]{X509}, new SecureRandom()); + return sslContext.getSocketFactory(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + + //获取HostnameVerifier + public static HostnameVerifier getHostnameVerifier() { + HostnameVerifier hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String s, SSLSession sslSession) { + return true; + } + }; + return hostnameVerifier; + } +} diff --git a/src/main/java/com/bootdo/util/NumKit.java b/src/main/java/com/bootdo/util/NumKit.java new file mode 100644 index 0000000..8cb9d79 --- /dev/null +++ b/src/main/java/com/bootdo/util/NumKit.java @@ -0,0 +1,51 @@ +package com.bootdo.util; + +import java.math.BigDecimal; + +public class NumKit { + + public NumKit() { + } + + + public static Double checkDouble(String num) { + try { + Double i = Double.valueOf(num); + return i; + } catch (Exception var3) { + } + + return 0D; + } + + public static Integer checkInt(String num) { + try { + Integer i = Integer.valueOf(num); + return i; + } catch (Exception var3) { + } + return 0; + } + + public static Long checkLong(String num) { + try { + Long i = Long.valueOf(num); + return i; + } catch (Exception var3) { + } + return 0L; + } + + public static BigDecimal checkBigDecimal(String num) { + try { + BigDecimal bd = new BigDecimal(num); + return bd; + } catch (Exception var3) { + } + return null; + } + + + + +} diff --git a/src/main/java/com/bootdo/util/OrderedProperties.java b/src/main/java/com/bootdo/util/OrderedProperties.java new file mode 100644 index 0000000..c43e9b1 --- /dev/null +++ b/src/main/java/com/bootdo/util/OrderedProperties.java @@ -0,0 +1,38 @@ +package com.bootdo.util; + +import java.util.*; + +/** + * OrderedProperties + * @author Unmi + * @date 2012-12-07 + */ +public class OrderedProperties extends Properties { + + private static final long serialVersionUID = -4627607243846121965L; + + private final LinkedHashSet keys = new LinkedHashSet(); + + public Enumeration keys() { + return Collections. enumeration(keys); + } + + public Object put(Object key, Object value) { + keys.add(key); + return super .put(key, value); + } + + public Set keySet() { + return keys; + } + + public Set stringPropertyNames() { + Set set = new LinkedHashSet(); + + for (Object key : this .keys) { + set.add((String) key); + } + + return set; + } +} \ No newline at end of file diff --git a/src/main/java/com/bootdo/util/PicFile.java b/src/main/java/com/bootdo/util/PicFile.java new file mode 100644 index 0000000..d2fc09f --- /dev/null +++ b/src/main/java/com/bootdo/util/PicFile.java @@ -0,0 +1,134 @@ +package com.bootdo.util; + +import org.apache.commons.lang3.StringUtils; +import org.apache.tomcat.util.codec.binary.Base64; +import sun.misc.BASE64Decoder; + +import javax.imageio.ImageIO; +import javax.xml.bind.DatatypeConverter; +import java.awt.image.BufferedImage; +import java.io.*; + +/** + * 生成图片工具类 + */ +public class PicFile { + + private static BASE64Decoder decoder = new BASE64Decoder(); + + /** + * 生成图片 + */ + public static boolean generateImage1(String filePath, String imgBase64Str, String fileName) { + if (StringUtils.isBlank(filePath)) { + return false; + } + if (StringUtils.isBlank(imgBase64Str)) { + return false; + } + if (StringUtils.isBlank(fileName)) { + return false; + } + try { + byte[] b = decoder.decodeBuffer(imgBase64Str); + ByteArrayInputStream inputStream = new ByteArrayInputStream(b); + File file = new File(filePath); + if (!file.exists()) { + file.mkdirs(); + } + if (!filePath.endsWith("/")) { + filePath = filePath + "/"; + } + File f = new File(filePath + fileName); + BufferedImage bi = ImageIO.read(inputStream); + ImageIO.write(bi, "jpg", f); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * base64转图片 + */ + public static boolean generateImage(String filePath, String imgBase64Str, String fileName) { + if (StringUtils.isBlank(filePath)) { + return false; + } + if (StringUtils.isBlank(imgBase64Str)) { + return false; + } + if (StringUtils.isBlank(fileName)) { + return false; + } + BufferedImage image = null; + byte[] imageByte = null; + try { + imageByte = DatatypeConverter.parseBase64Binary(imgBase64Str); + ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); + image = ImageIO.read(new ByteArrayInputStream(imageByte)); + bis.close(); + File outPutFile = new File(filePath + fileName); + ImageIO.write(image, "jpg", outPutFile); + } catch (IOException e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * base64转图片 + */ + public static boolean generateImage(String filePathName, String imgBase64Str) { + if (StringUtils.isBlank(filePathName)) { + return false; + } + if (StringUtils.isBlank(imgBase64Str)) { + return false; + } + BufferedImage image = null; + byte[] imageByte = null; + try { + imageByte = DatatypeConverter.parseBase64Binary(imgBase64Str); + ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); + image = ImageIO.read(new ByteArrayInputStream(imageByte)); + bis.close(); + File outPutFile = new File(filePathName + ".tmp"); + String fileFolder = outPutFile.getParent(); + File folderFile = new File(fileFolder); + if(!folderFile.exists()){ + folderFile.mkdirs(); + } + + ImageIO.write(image, "jpg", outPutFile); + outPutFile.renameTo(new File(filePathName)); + } catch (IOException e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 将图片转换成Base64编码 + */ + public static String getImgStr(String imgFile) { + //将图片文件转化为字节数组字符串,并对其进行Base64编码处理 + InputStream in = null; + byte[] data = null; + //读取图片字节数组 + try { + in = new FileInputStream(imgFile); + data = new byte[in.available()]; + in.read(data); + in.close(); + } catch (IOException e) { + e.printStackTrace(); + return ""; + } + return new String(Base64.encodeBase64(data)); + } + +} diff --git a/src/main/java/com/bootdo/util/PropertiesUtil.java b/src/main/java/com/bootdo/util/PropertiesUtil.java new file mode 100644 index 0000000..eab1340 --- /dev/null +++ b/src/main/java/com/bootdo/util/PropertiesUtil.java @@ -0,0 +1,189 @@ +package com.bootdo.util; + + +import org.apache.commons.lang3.StringUtils; + +import java.io.*; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * 读取Properties综合类,默认绑定到classpath下的config.properties文件。 + * + * @author 朱志杰 QQ:695520848 + */ +public class PropertiesUtil { + //配置文件的路径 + private String configPath = "config"+File.separator+"application.properties"; + public static final String Path = "config"+File.separator+"application.properties"; + + /** + * 配置文件对象 + */ + private Properties props = null; + + /** + * 默认构造函数,用于sh运行,自动找到classpath下的config.properties。 + */ + public PropertiesUtil() throws IOException { + InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("application.properties"); + props = new Properties(); + props.load(in); + //关闭资源 + in.close(); + } + + /** + * 根据key值读取配置的值 + * Jun 26, 2010 9:15:43 PM + * + * @param key key值 + * @return key 键对应的值 + * @throws IOException + * @author 朱志杰 + */ + public String readValue(String key) throws IOException { + return props.getProperty(key); + } + + /** + * 读取properties的全部信息 + * Jun 26, 2010 9:21:01 PM + * + * @throws FileNotFoundException 配置文件没有找到 + * @throws IOException 关闭资源文件,或者加载配置文件错误 + * @author 朱志杰 + */ + public Map readAllProperties() throws FileNotFoundException, IOException { + //保存所有的键值 + Map map = new HashMap(); + Enumeration en = props.propertyNames(); + while (en.hasMoreElements()) { + String key = (String) en.nextElement(); + String Property = props.getProperty(key); + map.put(key, Property); + } + return map; + } + + /** + * 设置某个key的值,并保存至文件。 + * Jun 26, 2010 9:15:43 PM + * + * @param key key值 + * @return key 键对应的值 + * @throws IOException + * @author 朱志杰 + */ + public void setValue(String key, String value) throws IOException { + Properties prop = new Properties(); + InputStream fis = new FileInputStream(this.configPath); + // 从输入流中读取属性列表(键和元素对) + prop.load(fis); + // 调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。 + // 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。 + OutputStream fos = new FileOutputStream(this.configPath); + prop.setProperty(key, value); + // 以适合使用 load 方法加载到 Properties 表中的格式, + // 将此 Properties 表中的属性列表(键和元素对)写入输出流 + prop.store(fos, "last update"); + //关闭文件 + fis.close(); + fos.close(); + } + + /** + * 读取配置文件中key的对应值 + * + * @param key + * @return + */ + public static String queryPropertiesByKey(String key) { + if (StringUtils.isBlank(key)) return ""; + Properties properties = new Properties(); + // 使用InPutStream流读取properties文件 + BufferedReader bufferedReader = null; + try { + bufferedReader = new BufferedReader(new FileReader(Path)); + properties.load(bufferedReader); + String rel = properties.getProperty(key); + bufferedReader.close(); + // 获取key对应的value值 + return rel; + } catch (IOException e) { + if(null != bufferedReader){ + try { + bufferedReader.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + e.printStackTrace(); + } + if(null != bufferedReader){ + try { + bufferedReader.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + return ""; + } + + /** + * 设置配置文件key的value值 + * + * @param key + * @param value + */ + public static void setPropertiesByKey(String key, String value) { +// String realpath = ClassUtils.getDefaultClassLoader().getResource("").getPath(); + File file = new File(Path); + OrderedProperties properties = new OrderedProperties(); + try { + properties.load(new FileInputStream(file)); + properties.setProperty(key, value); + FileOutputStream oFile = new FileOutputStream(Path);//true表示追加打开 + properties.store(oFile, "The New properties file"); + oFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * 读取配置文件中key的对应值 + * + * @param key + * @return + */ + public static String queryValue(String key) { + if (StringUtils.isBlank(key)) return ""; + Properties properties = new Properties(); + BufferedReader bufferedReader = null; + String rel = ""; + try { + bufferedReader = new BufferedReader(new FileReader(Path)); + properties.load(bufferedReader); + rel = properties.getProperty(key); + if (StringUtils.isNotBlank(rel)) { + rel = rel.trim(); + } + bufferedReader.close(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (null != bufferedReader) { + try { + bufferedReader.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + } + return rel; + } + +} \ No newline at end of file diff --git a/src/main/java/com/bootdo/util/RandomUtils.java b/src/main/java/com/bootdo/util/RandomUtils.java new file mode 100644 index 0000000..1feac1d --- /dev/null +++ b/src/main/java/com/bootdo/util/RandomUtils.java @@ -0,0 +1,57 @@ +package com.bootdo.util; + +import java.util.Random; + +public class RandomUtils { + /** + * 获取从a至z,长度为length随机数 + * + * @return + */ + public static String getRandomStr(int length) { + String base = "abcdefghijklmnopqrstuvwxyz"; + Random random = new Random(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < length; i++) { + int number = random.nextInt(base.length()); + sb.append(base.charAt(number)); + } + return sb.toString(); + } + + /** + * 获取随机长度随机字符 + * + * @param length + * @return + */ + public static String getRandomString(int length) { // length表示生成字符串的长度 + String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + Random random = new Random(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < length; i++) { + int number = random.nextInt(base.length()); + sb.append(base.charAt(number)); + } + return sb.toString(); + } + + /** + * 获取随机长度随机数字 + * + * @param length + * @return + */ + public static String getRandomNumString(int length) { // length表示生成字符串的长度 + String base = "0123456789"; + Random random = new Random(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < length; i++) { + int number = random.nextInt(base.length()); + sb.append(base.charAt(number)); + } + return sb.toString(); + } + + +} diff --git a/src/main/java/com/bootdo/util/SHAUtil.java b/src/main/java/com/bootdo/util/SHAUtil.java new file mode 100644 index 0000000..c2a35a8 --- /dev/null +++ b/src/main/java/com/bootdo/util/SHAUtil.java @@ -0,0 +1,65 @@ +package com.bootdo.util; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * ant 加密 工具类 + * + * @author bc + * @Date 2020-08-12 9:34 + */ +public class SHAUtil { + + public static String sha1(String decript) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-1"); + digest.update(decript.getBytes()); + byte[] messageDigest = digest.digest(); + // Create Hex String + StringBuffer hexString = new StringBuffer(); + // 字节数组转换为 十六进制 数 + for (int i = 0; i < messageDigest.length; i++) { + String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); + if (shaHex.length() < 2) { + hexString.append(0); + } + hexString.append(shaHex); + } + return hexString.toString(); + } catch (NoSuchAlgorithmException e) { + System.out.println("字节数组转换异常" + e); + } + return ""; + } + + /** + * 南京鸿信 + * + * @return + */ + public static Map getHeaders() { + Map map = Collections.synchronizedMap(new HashMap<>(5)); + String decript = ""; + String appId = PropertiesUtil.queryPropertiesByKey("APPID"); + String appKey = PropertiesUtil.queryPropertiesByKey("APPKEY"); + String nonce = UUID.randomUUID().toString().replace("-", ""); + String curTime = String.valueOf(System.currentTimeMillis()); + decript = nonce + appKey + curTime; + String checkNum = sha1(decript); + System.out.println("appId:" + appId + ", appKey:" + appKey + ", nonce:" + nonce + ", curTime:" + curTime + ", checkNum:" + checkNum); + map.put("appId", appId); + map.put("appKey", appKey); + map.put("nonce", nonce); + map.put("curTime", curTime); + map.put("checkNum", checkNum); + return map; + } + + + +} diff --git a/src/main/java/com/bootdo/util/SSLSocketClient.java b/src/main/java/com/bootdo/util/SSLSocketClient.java new file mode 100644 index 0000000..42fecfc --- /dev/null +++ b/src/main/java/com/bootdo/util/SSLSocketClient.java @@ -0,0 +1,62 @@ +package com.bootdo.util; + +import javax.net.ssl.*; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.util.Arrays; + +public class SSLSocketClient { + //获取这个SSLSocketFactory + public static SSLSocketFactory getSSLSocketFactory() { + try { + SSLContext sslContext = SSLContext.getInstance("SSL"); + sslContext.init(null, getTrustManager(), new SecureRandom()); + return sslContext.getSocketFactory(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + //获取TrustManager + private static TrustManager[] getTrustManager() { + 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[]{}; + } + } + }; + } + + //获取HostnameVerifier + public static HostnameVerifier getHostnameVerifier() { + return (s, sslSession) -> true; + } + + public static X509TrustManager getX509TrustManager() { + X509TrustManager trustManager = null; + try { + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init((KeyStore) null); + TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); + if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { + throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); + } + trustManager = (X509TrustManager) trustManagers[0]; + } catch (Exception e) { + e.printStackTrace(); + } + + return trustManager; + } +} \ No newline at end of file diff --git a/src/main/java/com/bootdo/util/SslUtils.java b/src/main/java/com/bootdo/util/SslUtils.java new file mode 100644 index 0000000..7736463 --- /dev/null +++ b/src/main/java/com/bootdo/util/SslUtils.java @@ -0,0 +1,61 @@ +package com.bootdo.util; + +import javax.net.ssl.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +/** + * + * @author Miss.Ru + * + */ +public class SslUtils { + private static void trustAllHttpsCertificates() throws Exception { + TrustManager[] trustAllCerts = new TrustManager[1]; + TrustManager tm = new miTM(); + trustAllCerts[0] = tm; + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, null); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); +} + +static class miTM implements TrustManager,X509TrustManager { + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + public boolean isServerTrusted(X509Certificate[] certs) { + return true; + } + + public boolean isClientTrusted(X509Certificate[] certs) { + return true; + } + + public void checkServerTrusted(X509Certificate[] certs, String authType) + throws CertificateException { + return; + } + + public void checkClientTrusted(X509Certificate[] certs, String authType) + throws CertificateException { + return; + } +} + +/** + * 忽略HTTPS请求的SSL证书,必须在openConnection之前调用 + * @throws Exception + */ +public static void ignoreSsl() throws Exception{ + HostnameVerifier hv = new HostnameVerifier() { + public boolean verify(String urlHostName, SSLSession session) { + System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); + return true; + } + }; + trustAllHttpsCertificates(); + HttpsURLConnection.setDefaultHostnameVerifier(hv); + } +} + diff --git a/src/main/java/com/bootdo/util/StringKit.java b/src/main/java/com/bootdo/util/StringKit.java new file mode 100644 index 0000000..15a0b5d --- /dev/null +++ b/src/main/java/com/bootdo/util/StringKit.java @@ -0,0 +1,103 @@ +package com.bootdo.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.regex.Pattern; + +public class StringKit { + + private static final Logger logger = LoggerFactory.getLogger(StringKit.class); + + public StringKit() { + } + + public static Boolean isEmpty(Object argObject) { + Boolean tbool = false; + String tString = toString(argObject); + if (tString.equals("")) { + tbool = true; + } + + return tbool; + } + + public static String toString(Object argObject) { + String tmpstr = ""; + try { + if (argObject != null) { + tmpstr = argObject.toString(); + if ("null".equals(tmpstr) || "underfind".equals(tmpstr) || "undefined".equals(tmpstr) || "{}".equals(tmpstr)) { + tmpstr = ""; + } + } + } catch (Exception var3) { + } + + return tmpstr; + } + + + public static boolean isNumeric(String str) { + Pattern pattern = Pattern.compile("[0-9]*"); + return pattern.matcher(str).matches(); + } + + public static boolean isEng(String str) { + Pattern pattern = Pattern.compile("[a-zA-Z]"); + return pattern.matcher(str).matches(); + } + + + public static String getTrace(Throwable t) { + + StringWriter stringWriter = new StringWriter(); + PrintWriter writer = new PrintWriter(stringWriter); + t.printStackTrace(writer); + StringBuffer buffer = stringWriter.getBuffer(); + return buffer.toString(); + } + + /** + * 空时 返回NA(有的厂家字段必填,我们没有,先用NA补充) + * + * @return + */ + public static String responseNa(Object object) { + if (isEmpty(object)) { + return "NA"; + } + return String.valueOf(object); + } + + /** + * 检查某个字符串出现几次 + * + * @return + */ + public static Integer getStrCount(String str, String indexStr) { + + //java中判断一个字符出现的次数 + //在下面字符串中查找有几个啊 +// String str = "啊!我爱你中国!啊,我爱你故乡"; + //存放每个字符的数组 + String[] strs = new String[str.length()]; + //计数该字符出现了多少次 + int count = 0; + //先把字符串转换成数组 + for (int i = 0; i < strs.length; i++) { + strs[i] = str.substring(i, i + 1); + } + //挨个字符进行查找,查找到之后count++ + for (int i = 0; i < strs.length; i++) { + if (strs[i].equals(indexStr)) { + count++; + } + } +// System.out.println("一共有"+count+"个啊"); + return count; + + } +} diff --git a/src/main/java/com/bootdo/util/ValidUtil.java b/src/main/java/com/bootdo/util/ValidUtil.java new file mode 100644 index 0000000..0fbf374 --- /dev/null +++ b/src/main/java/com/bootdo/util/ValidUtil.java @@ -0,0 +1,298 @@ +package com.bootdo.util; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class ValidUtil { + + private static final Logger log = LoggerFactory.getLogger(ValidUtil.class); + private static final String SM = "SM"; + private static final String FSM = "FSM"; + private static final int VILLAGE_CODE_LENGTH = 15; + + /** + * 校验身份证号 + * + * @param idCard + * @return + */ + public String checkIdCard(String idCard) { + if (StringUtils.isBlank(idCard)) { + return ""; + } + if (idCard.length() != 18) { + return ""; + } + return idCard.trim(); + } + + /** + * 检测是否带眼镜 + * + * @param glasses + * @return + */ + public String checkGlasses(String glasses) { + if (StringUtils.isBlank(glasses)) { + return "0"; + } + int glassInt = 0; + try { + glassInt = Integer.parseInt(glasses); + } catch (Exception e) { + return "0"; + } + if (glassInt == 0 || glassInt == 1 || glassInt == 2) { + glasses = String.valueOf(glassInt); + } else { + return "0"; + } + return glasses; + } + + /** + * 是否戴帽子 + * + * @param hat + * @return + */ + public String checkHat(String hat) { + if (StringUtils.isBlank(hat)) { + return "0"; + } + int hatInt = 0; + try { + hatInt = Integer.parseInt(hat); + } catch (Exception e) { + return "0"; + } + if (hatInt == 0 || hatInt == 1 || hatInt == 2) { + hat = String.valueOf(hatInt); + } else { + return "0"; + } + return hat; + } + + /** + * 是否戴口罩 + * + * @param mask + * @return + */ + public String checkMask(String mask) { + if (StringUtils.isBlank(mask)) { + return "0"; + } + int maskInt = 0; + try { + maskInt = Integer.parseInt(mask); + } catch (Exception e) { + return "0"; + } + if (maskInt == 0 || maskInt == 1 || maskInt == 2) { + mask = String.valueOf(maskInt); + } else { + return "0"; + } + return mask; + } + + /** + * 档案编号 + * + * @param dossierCode + * @return + */ + public String checkDossierCode(String dossierCode) { + if (StringUtils.isBlank(dossierCode) || dossierCode.equals("0")) { + return ""; + } + int dossierCodeInt = 0; + try { + dossierCodeInt = Integer.parseInt(dossierCode); + } catch (Exception e) { + return ""; + } + return String.valueOf(dossierCodeInt); + } + + /** + * 相似度 + * + * @param similarity + * @return + */ + public String checkSimilarity(String similarity) { + if (StringUtils.isBlank(similarity) || similarity.equals("0")) { + return ""; + } + int similarityInt = 0; + try { + similarityInt = Integer.parseInt(similarity); + } catch (Exception e) { + return ""; + } + return String.valueOf(similarityInt); + } + + public String checkIvsDeviceCode(String isvCode) { + if (StringUtils.isBlank(isvCode) || isvCode.equals("0")) { + return ""; + } + return String.valueOf(isvCode.trim()); + } + + /** + * 入库档案编号 + * ivsCode ivs服务器SN + * dossierCode 样本库和陌生人库id + */ + public String dealDossierCode(String ivsCode, String idCard, String dossierCode) { + if (StringUtils.isBlank(ivsCode) + || StringUtils.isBlank(dossierCode) + || "0".equals(ivsCode)) { + return ""; + } + if (StringUtils.isBlank(idCard)) { + return FSM + "-" + ivsCode + "-" + dossierCode; + } else { + return SM + "-" + ivsCode + "-" + dossierCode; + } + } + + + /** + * 人脸比对结果 + * 1比对成功 2比对失败 3未比对 + * + * @param idCard + * @return + */ + public int dealCompare(String idCard) { + if (StringUtils.isBlank(idCard)) { + return 3; + } + if (idCard.length() == 18) { + return 1; + } + return 2; + } + + public boolean checkTime(String time) { + try { + if (StringUtils.isBlank(time) + || time.length() != 10) { + log.error("checkTime time:" + time); + return false; + } + String s = DateTool.yearMonthDay(time); + if (StringUtils.isBlank(s) || s.contains("-00")) { + return false; + } + } catch (Exception e) { + log.error("checkTime Exception:" + e.getMessage()); + return false; + } + return true; + } + + /** + * 车牌颜色 + * + * @param color + * @return + */ + public int dealPlateColor(String color) { + if (StringUtils.isBlank(color)) { + return 7; + } + if ("黄".equals(color) || "黄色".equals(color)) { + return 1; + } + if ("蓝".equals(color) || "蓝色".equals(color)) { + return 2; + } + if ("白".equals(color) || "白色".equals(color)) { + return 3; + } + if ("黑".equals(color) || "黑色".equals(color)) { + return 4; + } + if ("绿".equals(color) || "绿色".equals(color)) { + return 5; + } + if ("黄绿".equals(color) || "黄绿色".equals(color)) { + return 6; + } + return 7; + } + + /** + * 车身颜色 + * + * @param color + * @return + */ + public int dealVehicleColor(String color) { + if (StringUtils.isBlank(color)) { + return 99; + } + if ("黑".equals(color) || "黑色".equals(color)) { + return 1; + } + if ("白".equals(color) || "白色".equals(color)) { + return 2; + } + if ("灰".equals(color) || "灰色".equals(color)) { + return 3; + } + if ("红".equals(color) || "红色".equals(color)) { + return 4; + } + if ("蓝".equals(color) || "蓝色".equals(color)) { + return 5; + } + if ("黄".equals(color) || "黄色".equals(color)) { + return 6; + } + if ("橙".equals(color) || "橙色".equals(color)) { + return 7; + } + if ("棕".equals(color) || "棕色".equals(color)) { + return 8; + } + if ("绿".equals(color) || "绿色".equals(color)) { + return 9; + } + if ("紫".equals(color) || "紫色".equals(color)) { + return 10; + } + if ("青".equals(color) || "青色".equals(color)) { + return 11; + } + if ("粉".equals(color) || "粉色".equals(color)) { + return 12; + } + if ("透明".equals(color) || "透明色".equals(color)) { + return 13; + } + return 99; + } + + public String checkVillageCode(String villageCode) { + if (StringUtils.isBlank(villageCode)) { + return ""; + } + villageCode = villageCode.trim(); + if (villageCode.length() != VILLAGE_CODE_LENGTH) { + return ""; + } + return villageCode; + } + + +} diff --git a/src/main/java/com/bootdo/util/config/AsyncConfig.java b/src/main/java/com/bootdo/util/config/AsyncConfig.java new file mode 100644 index 0000000..67dc958 --- /dev/null +++ b/src/main/java/com/bootdo/util/config/AsyncConfig.java @@ -0,0 +1,35 @@ +package com.bootdo.util.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.TaskExecutor; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.ThreadPoolExecutor; + +@Configuration +@EnableAsync +public class AsyncConfig { + + @Bean + public TaskExecutor taskExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + // 设置核心线程数 + executor.setCorePoolSize(5); + // 设置最大线程数 + executor.setMaxPoolSize(10); + // 设置队列容量 + executor.setQueueCapacity(20); + // 设置线程活跃时间(秒) + executor.setKeepAliveSeconds(60); + // 设置默认线程名称 + executor.setThreadNamePrefix("lawrence-"); + // 设置拒绝策略 + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); + // 等待所有任务结束后再关闭线程池 + executor.setWaitForTasksToCompleteOnShutdown(true); + return executor; + } + +} \ No newline at end of file diff --git a/src/main/java/com/bootdo/util/config/Text.java b/src/main/java/com/bootdo/util/config/Text.java new file mode 100644 index 0000000..0014e4b --- /dev/null +++ b/src/main/java/com/bootdo/util/config/Text.java @@ -0,0 +1,14 @@ +package com.bootdo.util.config; + +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +@Component +public class Text { + + @Async + public void sayHellot(int i){ +// System.out.println(i+"---"+System.currentTimeMillis()); + } + +} \ No newline at end of file diff --git a/src/main/java/com/bootdo/util/kafka/ProducerDemo.java b/src/main/java/com/bootdo/util/kafka/ProducerDemo.java new file mode 100644 index 0000000..218d2a9 --- /dev/null +++ b/src/main/java/com/bootdo/util/kafka/ProducerDemo.java @@ -0,0 +1,68 @@ +//package com.bootdo.util.kafka; +// +//import java.util.Properties; +// +//import com.alibaba.fastjson.JSONObject; +//import com.bootdo.dataaccess.dianxin.domain.dfwl.DfwlVehicleRecord; +//import org.apache.kafka.clients.producer.KafkaProducer; +//import org.apache.kafka.clients.producer.ProducerRecord; +// +//public class ProducerDemo { +// +// private final KafkaProducer producer; +// +// public final static String TOPIC = "third_vehicle_access_log"; +// +// private ProducerDemo() { +// Properties props = new Properties(); +// props.put("bootstrap.servers", "32.132.2.71:9092");//xxx服务器ip +//// props.put("bootstrap.servers", "xxx:9092,1xxx:9092,xxx:9092");//xxx服务器ip +// props.put("acks", "all");//所有follower都响应了才认为消息提交成功,即"committed" +// props.put("retries", 0);//retries = MAX 无限重试,直到你意识到出现了问题:) +// props.put("batch.size", 16384);//producer将试图批处理消息记录,以减少请求次数.默认的批量处理消息字节数 +// //batch.size当批量的数据大小达到设定值后,就会立即发送,不顾下面的linger.ms +// props.put("linger.ms", 1);//延迟1ms发送,这项设置将通过增加小的延迟来完成--即,不是立即发送一条记录,producer将会等待给定的延迟时间以允许其他消息记录发送,这些消息记录可以批量处理 +// props.put("buffer.memory", 33554432);//producer可以用来缓存数据的内存大小。 +// props.put("key.serializer", +// "org.apache.kafka.common.serialization.IntegerSerializer"); +// props.put("value.serializer", +// "org.apache.kafka.common.serialization.StringSerializer"); +// +// producer = new KafkaProducer(props); +// } +// +// public void produce() { +// int messageNo = 1; +// final int COUNT = 5; +// +// while(messageNo < COUNT) { +// String key = String.valueOf(messageNo); +// +// DfwlVehicleRecord newBean = new DfwlVehicleRecord() ; +// newBean.setEquipmentIP("192.168.11.2"); +// newBean.setVillageCode("WT_320903_LYXC_2021052615"); +// newBean.setEnterOrOut("0"); +// newBean.setPlatePicUrl("url"); +// newBean.setCarUrl("url"); +// newBean.setSenceUrl("url"); +// newBean.setImageFormat("base64"); +// newBean.setPassTime("2021-01-01 00:00:00"); +// newBean.setPlateNo("1"); +// newBean.setAvObj("1"); +// newBean.setAvObjName("test"); +// newBean.setSource("4"); +// +// String data = String.format(JSONObject.toJSONString(newBean), key); +// +// try { +// producer.send(new ProducerRecord(TOPIC, data)); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// messageNo++; +// } +// +// producer.close(); +// } +// +//} \ No newline at end of file diff --git a/src/main/java/com/bootdo/util/kafka/UserKafkaConsumer.java b/src/main/java/com/bootdo/util/kafka/UserKafkaConsumer.java new file mode 100644 index 0000000..572d0ed --- /dev/null +++ b/src/main/java/com/bootdo/util/kafka/UserKafkaConsumer.java @@ -0,0 +1,35 @@ +//package com.bootdo.util.kafka; +//import java.util.Arrays; +//import java.util.Properties; +// +//import org.apache.kafka.clients.consumer.ConsumerRecord; +//import org.apache.kafka.clients.consumer.ConsumerRecords; +//import org.apache.kafka.clients.consumer.KafkaConsumer; +// +// +//public class UserKafkaConsumer extends Thread { +// +// public static void main(String[] args){ +// Properties properties = new Properties(); +// properties.put("bootstrap.servers", "32.132.2.71:9092");//xxx是服务器集群的ip +// properties.put("group.id", "jd-group"); +// properties.put("enable.auto.commit", "true"); +// properties.put("auto.commit.interval.ms", "1000"); +// properties.put("auto.offset.reset", "latest"); +// properties.put("session.timeout.ms", "30000"); +// properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); +// properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); +// +// KafkaConsumer kafkaConsumer = new KafkaConsumer<>(properties); +// kafkaConsumer.subscribe(Arrays.asList("test5")); +// while (true) { +// ConsumerRecords records = kafkaConsumer.poll(100); +// for (ConsumerRecord record : records) { +// System.out.println("-----------------"); +// System.out.printf("offset = %d, value = %s", record.offset(), record.value()); +// System.out.println(); +// } +// } +// +// } +//} \ No newline at end of file diff --git a/src/main/java/com/bootdo/util/safe/AESTools.java b/src/main/java/com/bootdo/util/safe/AESTools.java new file mode 100644 index 0000000..084a6fa --- /dev/null +++ b/src/main/java/com/bootdo/util/safe/AESTools.java @@ -0,0 +1,90 @@ +package com.bootdo.util.safe; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; + +/** + * @author daifei + * @Description: AES对称加密工具类 + * @date 2021年4月14日 + */ + +public class AESTools { + private static final Logger log = LoggerFactory.getLogger(AESTools.class); + private static final String KEY_ALGORITHM = "AES"; + private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";// 默认的加密算法 + + /** + * AES 加密操作 + * + * @param content 待加密内容 + * @param password 加密密码 + * @return 返回Base64转码后的加密数据 + */ + public static String encrypt(String content, String password) { + if (StringUtils.isBlank(content)) { + return ""; + } + try { + Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器 + + byte[] byteContent = content.getBytes("utf-8"); + + cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化为加密模式的密码器 + + byte[] result = cipher.doFinal(byteContent);// 加密 + + return Base64Tools.encodeToString(result);// 通过Base64转码返回 + } catch (Exception ex) { + log.error("AES加密失败:" + content); + return ""; + } + } + + /** + * AES 解密操作 + * + * @param content + * @param password + * @return + */ + public static String decrypt(String content, String password) { + if (StringUtils.isBlank(content)) { + return ""; + } + try { + // 实例化 + Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); + + // 使用密钥初始化,设置为解密模式 + cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password)); + + // 执行操作 + byte[] result = cipher.doFinal(Base64Tools.decodeFromString(content)); + return new String(result, "utf-8"); + } catch (Exception ex) { + log.error("AES解密失败:" + content); + return ""; + } + } + + /** + * 生成加密秘钥 + * + * @return + */ + private static SecretKeySpec getSecretKey(final String password) { + try { + return new SecretKeySpec(password.getBytes("UTF-8"), KEY_ALGORITHM);// 转换为AES专用密钥 + } catch (Exception ex) { + LoggerFactory.getLogger(AESTools.class).error("", ex); + throw new RuntimeException("生成加密秘钥"); + } + } + + +} diff --git a/src/main/java/com/bootdo/util/safe/AesConstant.java b/src/main/java/com/bootdo/util/safe/AesConstant.java new file mode 100644 index 0000000..0f1aea2 --- /dev/null +++ b/src/main/java/com/bootdo/util/safe/AesConstant.java @@ -0,0 +1,7 @@ +package com.bootdo.util.safe; + +public class AesConstant { + public static final String AES_COMMON = "watu2022G409watu"; + public static final String AES_PHONE = "phoneG409WaTuNj1"; + public static final String AES_ID_CARD = "idCardG409WaTuNj"; +} diff --git a/src/main/java/com/bootdo/util/safe/Base64Tools.java b/src/main/java/com/bootdo/util/safe/Base64Tools.java new file mode 100644 index 0000000..fa8f6cb --- /dev/null +++ b/src/main/java/com/bootdo/util/safe/Base64Tools.java @@ -0,0 +1,116 @@ +package com.bootdo.util.safe; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +public abstract class Base64Tools { + + private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; + + + /** + * Base64-encode the given byte array. + * + * @param src the original byte array + * @return the encoded byte array + */ + public static byte[] encode(byte[] src) { + if (src.length == 0) { + return src; + } + return Base64.getEncoder().encode(src); + } + + /** + * Base64-decode the given byte array. + * + * @param src the encoded byte array + * @return the original byte array + */ + public static byte[] decode(byte[] src) { + if (src.length == 0) { + return src; + } + return Base64.getDecoder().decode(src); + } + + /** + * Base64-encode the given byte array using the RFC 4648 + * "URL and Filename Safe Alphabet". + * + * @param src the original byte array + * @return the encoded byte array + * @since 4.2.4 + */ + public static byte[] encodeUrlSafe(byte[] src) { + if (src.length == 0) { + return src; + } + return Base64.getUrlEncoder().encode(src); + } + + /** + * Base64-decode the given byte array using the RFC 4648 + * "URL and Filename Safe Alphabet". + * + * @param src the encoded byte array + * @return the original byte array + * @since 4.2.4 + */ + public static byte[] decodeUrlSafe(byte[] src) { + if (src.length == 0) { + return src; + } + return Base64.getUrlDecoder().decode(src); + } + + /** + * Base64-encode the given byte array to a String. + * + * @param src the original byte array (may be {@code null}) + * @return the encoded byte array as a UTF-8 String + */ + public static String encodeToString(byte[] src) { + if (src.length == 0) { + return ""; + } + return new String(encode(src), DEFAULT_CHARSET); + } + + /** + * Base64-decode the given byte array from an UTF-8 String. + * + * @param src the encoded UTF-8 String + * @return the original byte array + */ + public static byte[] decodeFromString(String src) { + if (src.isEmpty()) { + return new byte[0]; + } + return decode(src.getBytes(DEFAULT_CHARSET)); + } + + /** + * Base64-encode the given byte array to a String using the RFC 4648 + * "URL and Filename Safe Alphabet". + * + * @param src the original byte array + * @return the encoded byte array as a UTF-8 String + */ + public static String encodeToUrlSafeString(byte[] src) { + return new String(encodeUrlSafe(src), DEFAULT_CHARSET); + } + + /** + * Base64-decode the given byte array from an UTF-8 String using the RFC 4648 + * "URL and Filename Safe Alphabet". + * + * @param src the encoded UTF-8 String + * @return the original byte array + */ + public static byte[] decodeFromUrlSafeString(String src) { + return decodeUrlSafe(src.getBytes(DEFAULT_CHARSET)); + } + +} diff --git a/src/main/java/com/bootdo/util/safe/SignAlgorithm.java b/src/main/java/com/bootdo/util/safe/SignAlgorithm.java new file mode 100644 index 0000000..afc4afa --- /dev/null +++ b/src/main/java/com/bootdo/util/safe/SignAlgorithm.java @@ -0,0 +1,64 @@ +package com.bootdo.util.safe; + +/** + * 签名算法类型 + */ +public enum SignAlgorithm { + + // The RSA signature algorithm + NONEwithRSA("NONEwithRSA", "RSA"), + + // The MD2/MD5 with RSA Encryption signature algorithm + MD2withRSA("MD2withRSA", "RSA"), + MD5withRSA("MD5withRSA", "RSA"), + + // The signature algorithm with SHA-* and the RSA + SHA1withRSA("SHA1withRSA", "RSA"), + SHA256withRSA("SHA256withRSA", "RSA"), + SHA384withRSA("SHA384withRSA", "RSA"), + SHA512withRSA("SHA512withRSA", "RSA"), + + // The Digital Signature Algorithm + NONEwithDSA("NONEwithDSA", "DSA"), + // The DSA with SHA-1 signature algorithm + SHA1withDSA("SHA1withDSA", "DSA"), + + // The ECDSA signature algorithms + NONEwithECDSA("NONEwithECDSA", "EC"), + SHA1withECDSA("SHA1withECDSA", "EC"), + SHA256withECDSA("SHA256withECDSA", "EC"), + SHA384withECDSA("SHA384withECDSA", "EC"), + SHA512withECDSA("SHA512withECDSA", "EC");// + + private String value; + private String type; + + /** + * 构造 + * + * @param value 算法字符表示,区分大小写 + * @param type XXXwithXXX算法的后半部分算法,如果为ECDSA,返回算法为EC + */ + private SignAlgorithm(String value, String type) { + this.value = value; + this.type = type; + } + + /** + * 获取算法字符串表示,区分大小写 + * + * @return 算法字符串表示 + */ + public String getValue() { + return this.value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/src/main/java/com/bootdo/util/safe/SignatureTools.java b/src/main/java/com/bootdo/util/safe/SignatureTools.java new file mode 100644 index 0000000..058e58d --- /dev/null +++ b/src/main/java/com/bootdo/util/safe/SignatureTools.java @@ -0,0 +1,89 @@ +package com.bootdo.util.safe; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +public class SignatureTools { + + private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; + + /** + * sha256WithRsa 加签 + * + * @param content 待签名的字符串 + * @param priKeyBase64 base64编码的私钥 + * @return base64编码的签名 + */ + public static String rsa256Sign(String content, String priKeyBase64) { + byte[] signed = sign(SignAlgorithm.SHA256withRSA, content.getBytes(DEFAULT_CHARSET), Base64Tools.decodeFromString(priKeyBase64)); + return Base64Tools.encodeToString(signed); + } + + /** + * sha256WithRsa 验签 + * + * @param content 待验签的字符串 + * @param pubKeyBase64 base64编码的公钥 + * @param signBase64 base64编码签名 + * @return 签名是否正确 + */ + public static boolean rsa256Verify(String content, String pubKeyBase64, String signBase64) { + return verify(SignAlgorithm.SHA256withRSA, content.getBytes(DEFAULT_CHARSET), Base64Tools.decodeFromString(signBase64), + Base64Tools.decodeFromString(pubKeyBase64)); + } + + public static byte[] sign(SignAlgorithm algorithm, byte[] content, byte[] key) { + try { + PrivateKey priKey = generatePrivateKey(algorithm, key); + java.security.Signature signature = java.security.Signature.getInstance(algorithm.getValue()); + signature.initSign(priKey); + signature.update(content); + byte[] signed = signature.sign(); + return signed; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static boolean verify(SignAlgorithm algorithm, byte[] content, byte[] sign, byte[] key) { + try { + java.security.Signature signature = java.security.Signature.getInstance(algorithm.getValue()); + PublicKey publicKey = generatePublicKey(algorithm, key); + signature.initVerify(publicKey); + signature.update(content); + return signature.verify(sign); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + public static PrivateKey generatePrivateKey(SignAlgorithm algorithmType, byte[] key) + throws InvalidKeySpecException, NoSuchAlgorithmException { + return generatePrivateKey(algorithmType, new PKCS8EncodedKeySpec(key)); + } + + public static PrivateKey generatePrivateKey(SignAlgorithm algorithmType, KeySpec keySpec) + throws InvalidKeySpecException, NoSuchAlgorithmException { + return KeyFactory.getInstance(algorithmType.getType()).generatePrivate(keySpec); + } + + public static PublicKey generatePublicKey(SignAlgorithm algorithm, byte[] key) + throws InvalidKeySpecException, NoSuchAlgorithmException { + return generatePublicKey(algorithm, new X509EncodedKeySpec(key)); + } + + public static PublicKey generatePublicKey(SignAlgorithm algorithm, KeySpec keySpec) + throws InvalidKeySpecException, NoSuchAlgorithmException { + return KeyFactory.getInstance(algorithm.getType()).generatePublic(keySpec); + } + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..06e07fb --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,60 @@ +spring: + datasource: #数据库 + type: com.alibaba.druid.pool.DruidDataSource + username: root + password: '1qaz!QAZ' + url: jdbc:mysql://221.229.107.118:30519/multidimensional_box?useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true&serverTimezone=GMT + driver-class-name: com.mysql.cj.jdbc.Driver + initialSize: 5 # 配置初始化大小、最小、最大 + minIdle: 5 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 30000 + validationQuery: SELECT 'x' + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + # 打开PSCache,并且指定每个连接上PSCache的大小。如果用Oracle,则把poolPreparedStatements配置为true,mysql可以配置为false。分库分表较多的数据库,建议配置为false。 + poolPreparedStatements: false + maxPoolPreparedStatementPerConnectionSize: 20 + # 配置监控统计拦截的filters,wall防sql注入,日志 + filters: stat, wall, log4j + main: + allow-circular-references: true + jpa: + show-sql: true + properties: + hibernate: + format_sql: true + rabbitmq: + host: 110.1.200.11 + port: 19000 + username: root + password: 'sm@rtC@m!n23ty' + dynamic: true + +#mybatis: +# type-aliases-package: com.bootdo.pretreatment.*.entity +# mapper-locations: classpath:mapper/*.xml,classpath:mapper/*/*.xml,classpath:mapper/*/*/*.xml +#wt: +# version: 1.0.0 + +mybatis: + configuration: + map-underscore-to-camel-case: true + mapper-locations: classpath:mapper/*.xml,classpath:mapper/*/*.xml,classpath:mapper/*/*/*.xml + typeAliasesPackage: com.bootdo.datasend.**.domain + +logging: + level: + org.hibernate.SQL: DEBUG + org.hibernate.type.descriptor.sql.BasicBinder: TRACE + +server: + port: 8301 + config: file:config/logback.xml + diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt new file mode 100644 index 0000000..de2209a --- /dev/null +++ b/src/main/resources/banner.txt @@ -0,0 +1,22 @@ +//////////////////////////////////////////////////////////////////// +// _ooOoo_ // +// o8888888o // +// 88" . "88 // +// (| ^_^ |) // +// O\ = /O // +// ____/`---'\____ // +// .' \\| |// `. // +// / \\||| : |||// \ // +// / _||||| -:- |||||- \ // +// | | \\\ - /// | | // +// | \_| ''\---/'' | | // +// \ .-\__ `-` ___/-. / // +// ___`. .' /--.--\ `. . ___ // +// ."" '< `.___\_<|>_/___.' >'"". // +// | | : `- \`.;`\ _ /`;.`/ - ` : | | // +// \ \ `-. \_ __\ /__ _/ .-` / / // +// ========`-.____`-.___\_____/___.-`____.-'======== // +// `=---=' // +// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // +// 佛祖保佑 永不宕机 永无BUG // +//////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/src/main/resources/lib/arcsoft-sdk-face-3.0.0.0.jar b/src/main/resources/lib/arcsoft-sdk-face-3.0.0.0.jar new file mode 100644 index 0000000..5f37c1e Binary files /dev/null and b/src/main/resources/lib/arcsoft-sdk-face-3.0.0.0.jar differ diff --git a/src/main/resources/lib/kotlin-stdlib-1.3.71.jar b/src/main/resources/lib/kotlin-stdlib-1.3.71.jar new file mode 100644 index 0000000..e9012cf Binary files /dev/null and b/src/main/resources/lib/kotlin-stdlib-1.3.71.jar differ diff --git a/src/main/resources/lib/okhttp-2.2.0.jar b/src/main/resources/lib/okhttp-2.2.0.jar new file mode 100644 index 0000000..aabcbaa Binary files /dev/null and b/src/main/resources/lib/okhttp-2.2.0.jar differ diff --git a/src/main/resources/lib/okhttp-4.9.1.jar b/src/main/resources/lib/okhttp-4.9.1.jar new file mode 100644 index 0000000..e0f95b2 Binary files /dev/null and b/src/main/resources/lib/okhttp-4.9.1.jar differ diff --git a/src/main/resources/lib/okio-2.8.0.jar b/src/main/resources/lib/okio-2.8.0.jar new file mode 100644 index 0000000..bac6c6e Binary files /dev/null and b/src/main/resources/lib/okio-2.8.0.jar differ diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..fbf3b30 --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,80 @@ + + + + + + + + + + + ${log.pattern} + + + + + + ${log.path}/info.log + + + + ${log.path}/%d{yyyy-MM-dd}.info.log + + true + 2 + + + ${log.pattern} + + + + INFO + + ACCEPT + + DENY + + + + + ${log.path}/error.log + + + + ${log.path}/%d{yyyy-MM-dd}.error.log + + true + 2 + + + ${log.pattern} + + + + ERROR + + ACCEPT + + DENY + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file