From c261925ef22d9f14f0b304c622cae69a20826931 Mon Sep 17 00:00:00 2001 From: zhangjing <924187658@qq.com> Date: Thu, 24 Oct 2024 11:14:24 +0800 Subject: [PATCH] =?UTF-8?q?feat=EF=BC=9A=E3=80=90=E6=B3=95=E7=A0=94?= =?UTF-8?q?=E9=99=A2=E6=8E=A5=E5=8F=A3=E6=B5=8B=E8=AF=95=E3=80=91=E6=8F=90?= =?UTF-8?q?=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 346 ++++++++ src/main/java/com/fxzy/warn/RunApplication.java | 19 + .../warn/common/conf/ConvertToMultipartFile.java | 63 ++ .../com/fxzy/warn/common/conf/ExecutorConfig.java | 36 + .../java/com/fxzy/warn/common/conf/Idempotent.java | 25 + .../common/conf/IdempotentControllerAspect.java | 96 +++ .../fxzy/warn/common/conf/MyMetaObjectHandler.java | 48 ++ .../fxzy/warn/common/conf/MybatisPlusConfig.java | 29 + .../com/fxzy/warn/common/conf/RedisConfig.java | 64 ++ .../java/com/fxzy/warn/common/conf/Swagger.java | 44 + .../java/com/fxzy/warn/common/conf/WebConfig.java | 70 ++ .../com/fxzy/warn/common/conf/WebInterceptor.java | 90 ++ .../warn/common/constants/EntityConstants.java | 37 + .../common/constants/LawResearchUrlConstants.java | 90 ++ .../warn/common/constants/RedisKeyConstants.java | 28 + .../common/constants/ResponseMsgConstants.java | 45 + .../fxzy/warn/common/filter/CrossDomainFilter.java | 57 ++ .../com/fxzy/warn/common/filter/XssFilter.java | 32 + .../filter/XssHttpServletRequestWrapper.java | 125 +++ .../fxzy/warn/common/request/RequestParameter.java | 67 ++ .../com/fxzy/warn/common/response/ApiResponse.java | 90 ++ .../fxzy/warn/common/response/ApiResponseT.java | 90 ++ .../com/fxzy/warn/common/response/StatusCode.java | 82 ++ src/main/java/com/fxzy/warn/common/util/AES.java | 107 +++ src/main/java/com/fxzy/warn/common/util/Demo.java | 28 + .../java/com/fxzy/warn/common/util/FileUtil.java | 454 ++++++++++ .../java/com/fxzy/warn/common/util/HttpUtil.java | 198 +++++ .../java/com/fxzy/warn/common/util/JWTUtil.java | 189 ++++ .../com/fxzy/warn/common/util/LawResearchUtil.java | 949 +++++++++++++++++++++ .../java/com/fxzy/warn/common/util/RedisUtil.java | 678 +++++++++++++++ .../com/fxzy/warn/common/util/ServletUtils.java | 34 + .../java/com/fxzy/warn/common/util/TimeUtil.java | 609 +++++++++++++ .../common/util/treeUtil/ForestNodeManager.java | 65 ++ .../common/util/treeUtil/ForestNodeMerger.java | 37 + .../com/fxzy/warn/common/util/treeUtil/INode.java | 22 + .../com/fxzy/warn/controller/TestController.java | 148 ++++ src/main/java/com/fxzy/warn/mapper/TestMapper.java | 15 + src/main/java/com/fxzy/warn/model/Test.java | 36 + .../java/com/fxzy/warn/service/TestService.java | 45 + .../fxzy/warn/service/impl/TestServiceImpl.java | 50 ++ src/main/resources/bootstrap-dev.yml | 60 ++ src/main/resources/bootstrap-prod.yml | 48 ++ src/main/resources/bootstrap.yml | 53 ++ src/main/resources/logback-spring.xml | 236 +++++ src/main/resources/mapper/TestMapper.xml | 8 + src/main/resources/ueditor.json | 52 ++ 46 files changed, 5794 insertions(+) create mode 100644 pom.xml create mode 100644 src/main/java/com/fxzy/warn/RunApplication.java create mode 100644 src/main/java/com/fxzy/warn/common/conf/ConvertToMultipartFile.java create mode 100644 src/main/java/com/fxzy/warn/common/conf/ExecutorConfig.java create mode 100644 src/main/java/com/fxzy/warn/common/conf/Idempotent.java create mode 100644 src/main/java/com/fxzy/warn/common/conf/IdempotentControllerAspect.java create mode 100644 src/main/java/com/fxzy/warn/common/conf/MyMetaObjectHandler.java create mode 100644 src/main/java/com/fxzy/warn/common/conf/MybatisPlusConfig.java create mode 100644 src/main/java/com/fxzy/warn/common/conf/RedisConfig.java create mode 100644 src/main/java/com/fxzy/warn/common/conf/Swagger.java create mode 100644 src/main/java/com/fxzy/warn/common/conf/WebConfig.java create mode 100644 src/main/java/com/fxzy/warn/common/conf/WebInterceptor.java create mode 100644 src/main/java/com/fxzy/warn/common/constants/EntityConstants.java create mode 100644 src/main/java/com/fxzy/warn/common/constants/LawResearchUrlConstants.java create mode 100644 src/main/java/com/fxzy/warn/common/constants/RedisKeyConstants.java create mode 100644 src/main/java/com/fxzy/warn/common/constants/ResponseMsgConstants.java create mode 100644 src/main/java/com/fxzy/warn/common/filter/CrossDomainFilter.java create mode 100644 src/main/java/com/fxzy/warn/common/filter/XssFilter.java create mode 100644 src/main/java/com/fxzy/warn/common/filter/XssHttpServletRequestWrapper.java create mode 100644 src/main/java/com/fxzy/warn/common/request/RequestParameter.java create mode 100644 src/main/java/com/fxzy/warn/common/response/ApiResponse.java create mode 100644 src/main/java/com/fxzy/warn/common/response/ApiResponseT.java create mode 100644 src/main/java/com/fxzy/warn/common/response/StatusCode.java create mode 100644 src/main/java/com/fxzy/warn/common/util/AES.java create mode 100644 src/main/java/com/fxzy/warn/common/util/Demo.java create mode 100644 src/main/java/com/fxzy/warn/common/util/FileUtil.java create mode 100644 src/main/java/com/fxzy/warn/common/util/HttpUtil.java create mode 100644 src/main/java/com/fxzy/warn/common/util/JWTUtil.java create mode 100644 src/main/java/com/fxzy/warn/common/util/LawResearchUtil.java create mode 100644 src/main/java/com/fxzy/warn/common/util/RedisUtil.java create mode 100644 src/main/java/com/fxzy/warn/common/util/ServletUtils.java create mode 100644 src/main/java/com/fxzy/warn/common/util/TimeUtil.java create mode 100644 src/main/java/com/fxzy/warn/common/util/treeUtil/ForestNodeManager.java create mode 100644 src/main/java/com/fxzy/warn/common/util/treeUtil/ForestNodeMerger.java create mode 100644 src/main/java/com/fxzy/warn/common/util/treeUtil/INode.java create mode 100644 src/main/java/com/fxzy/warn/controller/TestController.java create mode 100644 src/main/java/com/fxzy/warn/mapper/TestMapper.java create mode 100644 src/main/java/com/fxzy/warn/model/Test.java create mode 100644 src/main/java/com/fxzy/warn/service/TestService.java create mode 100644 src/main/java/com/fxzy/warn/service/impl/TestServiceImpl.java create mode 100644 src/main/resources/bootstrap-dev.yml create mode 100644 src/main/resources/bootstrap-prod.yml create mode 100644 src/main/resources/bootstrap.yml create mode 100644 src/main/resources/logback-spring.xml create mode 100644 src/main/resources/mapper/TestMapper.xml create mode 100644 src/main/resources/ueditor.json diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..e24541e --- /dev/null +++ b/pom.xml @@ -0,0 +1,346 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 1.5.6.RELEASE + + + gas.service + gas_service + 1.0-SNAPSHOT + gas_service + gas_service + + UTF-8 + UTF-8 + 1.8 + + 3.0.3.RELEASE + 2.1.0 + 23.3 + + + + + + org.apache.commons + commons-pool2 + 2.4.2 + + + + + mysql + mysql-connector-java + 8.0.11 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-aop + 2.5.1 + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + org.projectlombok + lombok + true + + + + org.apache.httpcomponents + httpclient + 4.5.12 + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.springframework.cloud + spring-cloud-context + 1.2.4.RELEASE + + + + + junit + junit + + + + + org.springframework.boot + spring-boot-devtools + false + + + + + com.alibaba + druid-spring-boot-starter + 1.1.21 + + + + + + com.dameng + DmJdbcDriver18 + 8.1.1.193 + + + + + com.baomidou + mybatis-plus-boot-starter + 3.3.2 + + + + + org.springframework.boot + spring-boot-starter-redis + 1.3.5.RELEASE + + + + + com.alibaba + fastjson + 1.2.83 + + + + + io.springfox + springfox-swagger-ui + 2.4.0 + + + + io.springfox + springfox-swagger2 + 2.4.0 + + + + + + org.apache.commons + commons-lang3 + 3.9 + + + commons-lang + commons-lang + 2.4 + + + + + commons-io + commons-io + 2.6 + + + + + + + io.netty + netty-all + 4.1.17.Final + + + + org.json + json + + + commons-fileupload + commons-fileupload + 1.3.2 + + + commons-codec + commons-codec + 1.14 + + + + com.google.code.gson + gson + 2.8.5 + + + + commons-io + commons-io + 2.11.0 + + + + + com.nimbusds + nimbus-jose-jwt + 6.0 + + + + + + + + + + + + cn.afterturn + easypoi-base + 3.0.3 + + + cn.afterturn + easypoi-web + 3.0.3 + + + + org.apache.poi + poi + 4.0.0 + + + org.apache.poi + poi-ooxml + 4.0.0 + + + org.apache.poi + poi-ooxml-schemas + 4.0.0 + + + + com.alibaba + easyexcel + 2.1.7 + + + + org.ehcache + ehcache + 3.7.1 + + + + + org.locationtech.proj4j + proj4j + 1.1.1 + + + + + + org.geotools + gt-shapefile + ${geotools.version} + + + + org.geotools + gt-swing + ${geotools.version} + + + + + org.springframework + spring-test + 5.3.2 + compile + + + + + + + + + + GeoSolutions + http://maven.geo-solutions.it/ + + + + + osgeo + OSGeo Release Repository + https://repo.osgeo.org/repository/release/ + false + true + + + osgeo-snapshot + OSGeo Snapshot Repository + https://repo.osgeo.org/repository/snapshot/ + true + false + + + + + alfresco + Activiti Releases + https://artifacts.alfresco.com/nexus/content/repositories/activiti-releases/ + + true + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + true + + + org.projectlombok + lombok + + + + + + + + + + + + diff --git a/src/main/java/com/fxzy/warn/RunApplication.java b/src/main/java/com/fxzy/warn/RunApplication.java new file mode 100644 index 0000000..4695964 --- /dev/null +++ b/src/main/java/com/fxzy/warn/RunApplication.java @@ -0,0 +1,19 @@ +package com.fxzy.warn; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.ServletComponentScan; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@ServletComponentScan +@EnableAsync +@EnableScheduling +public class RunApplication { + + public static void main(String[] args) { + SpringApplication.run(RunApplication.class, args); + } + +} diff --git a/src/main/java/com/fxzy/warn/common/conf/ConvertToMultipartFile.java b/src/main/java/com/fxzy/warn/common/conf/ConvertToMultipartFile.java new file mode 100644 index 0000000..9b80a4b --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/conf/ConvertToMultipartFile.java @@ -0,0 +1,63 @@ +package com.fxzy.warn.common.conf; +import org.springframework.web.multipart.MultipartFile; + +import java.io.*; + +public class ConvertToMultipartFile implements MultipartFile { + private byte[] fileBytes; + String name; + String originalFilename; + String contentType; + boolean isEmpty; + long size; + + public ConvertToMultipartFile(byte[] fileBytes, String name, String originalFilename, String contentType, + long size) { + this.fileBytes = fileBytes; + this.name = name; + this.originalFilename = originalFilename; + this.contentType = contentType; + this.size = size; + this.isEmpty = false; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getOriginalFilename() { + return originalFilename; + } + + @Override + public String getContentType() { + return contentType; + } + + @Override + public boolean isEmpty() { + return isEmpty; + } + + @Override + public long getSize() { + return size; + } + + @Override + public byte[] getBytes() throws IOException { + return fileBytes; + } + + @Override + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(fileBytes); + } + + @Override + public void transferTo(File dest) throws IOException, IllegalStateException { + new FileOutputStream(dest).write(fileBytes); + } +} diff --git a/src/main/java/com/fxzy/warn/common/conf/ExecutorConfig.java b/src/main/java/com/fxzy/warn/common/conf/ExecutorConfig.java new file mode 100644 index 0000000..4bdcea4 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/conf/ExecutorConfig.java @@ -0,0 +1,36 @@ +package com.fxzy.warn.common.conf; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; + +/** + * 线程池配置 + * @author yuyantian + * @date 2021/3/6 + */ +@Configuration +@EnableAsync +@Slf4j +public class ExecutorConfig { + + @Bean(name="asyncExecutor") + public Executor asyncServiceExecutor(){ + ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); + taskExecutor.setCorePoolSize(10); + taskExecutor.setMaxPoolSize(50); + taskExecutor.setQueueCapacity(200); + taskExecutor.setKeepAliveSeconds(60); + taskExecutor.setThreadNamePrefix("asyncExecutor-"); + taskExecutor.setWaitForTasksToCompleteOnShutdown(true); + taskExecutor.setAwaitTerminationSeconds(60); + return taskExecutor; + } + + + +} diff --git a/src/main/java/com/fxzy/warn/common/conf/Idempotent.java b/src/main/java/com/fxzy/warn/common/conf/Idempotent.java new file mode 100644 index 0000000..430ba54 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/conf/Idempotent.java @@ -0,0 +1,25 @@ +package com.fxzy.warn.common.conf; + +//@Target(ElementType.METHOD) +//@Retention(RetentionPolicy.RUNTIME) +public @interface Idempotent { + + String message() default "操作太频繁请稍后再试"; + + /** + * 默认值为 -1 则相同参数只能等上次调用完成后,才能进行下次调用 + * 值为 800 则2次调用间隔 800毫秒 + */ + long interval() default -1L; + + /** + * TODO 请求参数筛选 "$sign_$1.name,$2.age,$3.getHeaders().get("token")" + */ + String uniqueKey() default ""; + + /** + * TODO 值为 true 则如果两次请求是不同ip则通过 + */ + boolean ip() default false; + +} diff --git a/src/main/java/com/fxzy/warn/common/conf/IdempotentControllerAspect.java b/src/main/java/com/fxzy/warn/common/conf/IdempotentControllerAspect.java new file mode 100644 index 0000000..2db03d2 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/conf/IdempotentControllerAspect.java @@ -0,0 +1,96 @@ +package com.fxzy.warn.common.conf; + +import com.fxzy.warn.common.response.ApiResponse; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.Signature; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.Method; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 返回值为 {@link ApiResponse} 的 Controller 幂等性请求切面 + */ +//@Aspect +//@Component +public class IdempotentControllerAspect { + private static Logger LOGGER = LoggerFactory.getLogger(IdempotentControllerAspect.class); + + private final ConcurrentHashMap requests = new ConcurrentHashMap<>(); + + @Pointcut("execution(public * com.fxzy.warn.controller..*(..)) && @annotation(Idempotent)") + public void idempotentPointCut() {} + + @Around("idempotentPointCut()") + public Object around(ProceedingJoinPoint point) throws Throwable { + // 获取注解配置 + Idempotent idempotent = null; + // 参数值列表 + Object[] args = null; + String sign = null; + boolean error = false; + try { + Signature signature = point.getSignature(); + Class type = signature.getDeclaringType(); + String method = signature.getName(); + // 参数类型列表 + Class[] paramTypes = ((MethodSignature) signature).getParameterTypes(); + // 获取原始方法上的 MapCache 注解 + Method declaredMethod = type.getDeclaredMethod(method, paramTypes); + idempotent = declaredMethod.getAnnotation(Idempotent.class); + args = point.getArgs(); + sign = getProcessSign(type, method, args); + // LOGGER.info("ASPECT ... sign={}", sign); + } catch (Exception e) { + error = true; + LOGGER.error("切面反射错误:", e); + } + if (idempotent == null || args == null || sign == null || error) { + return point.proceed(); + } + Long lastBeginTime = requests.get(sign); + long now = System.currentTimeMillis(); + boolean canPass = false; + // 这里可改为 redis 锁 + synchronized (sign) { + canPass = requests.get(sign) == null + || (idempotent.interval() > 0 && now - lastBeginTime > idempotent.interval()); + if (canPass) { + requests.put(sign, now); + } + } + if (canPass) { + try { + return point.proceed(); + } finally { + // 可能执行时间过了 interval 被别的请求更新了 + if (requests.get(sign) != null && requests.get(sign) == now) { + requests.remove(sign); + } + } + } else { + // 频繁提交不可执行 + ApiResponse res = new ApiResponse(); + res.recordError(idempotent.message()); + return res; + } + } + + private String getProcessSign(Class type, String method, Object[] args) { + StringBuilder sign = new StringBuilder(); + sign.append(type.getName()) + .append('.') + .append(method); + sign.append('('); + for (int i = 0; i < args.length; i++) { + sign.append(args[i]).append(","); + } + sign.append(')'); + return sign.toString().intern(); + } + +} diff --git a/src/main/java/com/fxzy/warn/common/conf/MyMetaObjectHandler.java b/src/main/java/com/fxzy/warn/common/conf/MyMetaObjectHandler.java new file mode 100644 index 0000000..bc36fcd --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/conf/MyMetaObjectHandler.java @@ -0,0 +1,48 @@ +package com.fxzy.warn.common.conf; + +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import lombok.extern.slf4j.Slf4j; +import org.apache.ibatis.reflection.MetaObject; +import org.springframework.stereotype.Component; + +import java.util.Date; + +/** + * 自动填充类 + * + * @author yuyantian + * @date 2023/9/18 14:30 + */ +@Slf4j +@Component +public class MyMetaObjectHandler implements MetaObjectHandler { + + private MyMetaObjectHandler() { + + } + + // 新增的时候自动填充 + @Override + public void insertFill(MetaObject metaObject) { + //创建时间 + if (null == this.getFieldValByName("createTime", metaObject)) { + this.setFieldValByName("createTime", new Date(), metaObject); + } + //判断是否删除类型为字符串 + Class isDelType = metaObject.getGetterType("isDel"); + if (isDelType.getName().equals("java.lang.Integer")) { + //是否删除 + this.setFieldValByName("isDel", 0, metaObject); + } + } + + // 更新的时候后自动填充 + @Override + public void updateFill(MetaObject metaObject) { + //修改时间 + this.setFieldValByName("updateTime", new Date(), metaObject); + //操作时间 + this.setFieldValByName("operationTime", new Date(), metaObject); + } + +} \ No newline at end of file diff --git a/src/main/java/com/fxzy/warn/common/conf/MybatisPlusConfig.java b/src/main/java/com/fxzy/warn/common/conf/MybatisPlusConfig.java new file mode 100644 index 0000000..885a354 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/conf/MybatisPlusConfig.java @@ -0,0 +1,29 @@ +package com.fxzy.warn.common.conf; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * MybatisPlus配置类 + * + * @author yuyantian + * @date 2021/9/7 14:30 + */ +@Configuration +public class MybatisPlusConfig { + + /** + * MyBatisPlus分页插件配置 + * 说明:指定 MySQL 方言,如果不指定,则可能分页查询出现数据不准确 + */ + @Bean + public PaginationInterceptor paginationInterceptor() { + PaginationInterceptor page = new PaginationInterceptor(); + //指定 MySQL 方言,否则它可能不知道怎么写分页函数 + page.setDbType(DbType.KINGBASE_ES); + return page; + + } +} \ No newline at end of file diff --git a/src/main/java/com/fxzy/warn/common/conf/RedisConfig.java b/src/main/java/com/fxzy/warn/common/conf/RedisConfig.java new file mode 100644 index 0000000..9abc1bf --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/conf/RedisConfig.java @@ -0,0 +1,64 @@ +package com.fxzy.warn.common.conf; + + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cache.annotation.CachingConfigurerSupport; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +/** + * Redis 工具类 + * + * @author yuyantian + * @date 2021/9/7 14:30 + */ +@Configuration +@EnableCaching +@Component +public class RedisConfig extends CachingConfigurerSupport { + + @Value("${spring.redis.host}") + private String host; + + @Value("${spring.redis.port}") + private int port; + + @Value("${spring.redis.password}") + private String password; + + + @Value("${spring.redis.pool.timeout}") + private int timeout; + + @Value("${spring.redis.pool.max-total}") + private int maxTotal; + + @Value("${spring.redis.pool.max-idle}") + private int maxIdle; + + @Value("${spring.redis.pool.max-wait}") + private long maxWaitMillis; + + @Bean + public JedisPool redisPoolFactory() { + JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); + jedisPoolConfig.setMaxTotal(maxTotal); + jedisPoolConfig.setMaxIdle(maxIdle); + jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); + jedisPoolConfig.setTestOnBorrow(true);//使用时进行扫描,确保都可用 + jedisPoolConfig.setTestWhileIdle(true);//Idle时进行连接扫描 + jedisPoolConfig.setTestOnReturn(true);//还回线程池时进行扫描 + jedisPoolConfig.setMinEvictableIdleTimeMillis(60000 * 30); + jedisPoolConfig.setTimeBetweenEvictionRunsMillis(60000 * 30); + jedisPoolConfig.setNumTestsPerEvictionRun(-1); + JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password); + return jedisPool; + } + + +} + diff --git a/src/main/java/com/fxzy/warn/common/conf/Swagger.java b/src/main/java/com/fxzy/warn/common/conf/Swagger.java new file mode 100644 index 0000000..a9e64d6 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/conf/Swagger.java @@ -0,0 +1,44 @@ +package com.fxzy.warn.common.conf; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +/** + * swagger 配置类 + * + * @author yuyantian + * @date 2021/9/7 14:30 + */ +@Configuration +@EnableSwagger2 +@ConditionalOnProperty(name = "swagger.enable", havingValue = "true") +public class Swagger { + + @Value("${server.servlet-path}") + private String servletPath; + + @Bean + public Docket createSwaggerApi() { + return new Docket(DocumentationType.SWAGGER_2).apiInfo(myApi()).select().apis( + RequestHandlerSelectors.basePackage("com.lzrq.wx")).paths( + PathSelectors.any()) + .build().pathMapping(servletPath); + } + + public ApiInfo myApi() { + return new ApiInfoBuilder().title("泸州燃气-模板填报系统-rest接口") + .contact(new Contact("yuyantian", "http", "@qq.com")).description("demo rest接口") + .version("1.0") + .build(); + } +} diff --git a/src/main/java/com/fxzy/warn/common/conf/WebConfig.java b/src/main/java/com/fxzy/warn/common/conf/WebConfig.java new file mode 100644 index 0000000..171a950 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/conf/WebConfig.java @@ -0,0 +1,70 @@ +package com.fxzy.warn.common.conf; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; + +/** + * web拦截 + * + * @author yuyantian + * @date 2021/9/7 + */ + +@Configuration +public class WebConfig extends WebMvcConfigurationSupport { + + @Value("${file.fileUploadRootPath}") + private String fileUploadRootPath; + + @Value("${file.fileUploadPath}") + private String fileUploadPath; + + @Value("${springfox.documentation.swagger.v2.path:/v2/api-docs}") + private String swaggerDocs; + + @Override + protected void addInterceptors(InterceptorRegistry registry) { + // 除login外都拦截 + registry.addInterceptor(webInterceptor()) + .addPathPatterns("/**") + // springboot 错误路径 + .excludePathPatterns("/error") + // swagger: springfox.documentation.swagger.web.ApiResourceController + .excludePathPatterns("/configuration/security", "/configuration/ui", + "/swagger-resources") + // swagger: springfox.documentation.swagger2.web.Swagger2Controller + .excludePathPatterns(swaggerDocs) + // 静态资源不拦截 + .excludePathPatterns("/static/**", "swagger-ui.html", "/webjars/**", + "/" + fileUploadPath + "/**") + .excludePathPatterns("/weChat/*") + + ; + } + + @Override + protected void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/static/**") + .addResourceLocations("/static/"); + // swagger start + registry.addResourceHandler("swagger-ui.html") + .addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/"); + registry.addResourceHandler("/images/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/images/"); + // swagger end + //附件虚拟路径的配置 + registry.addResourceHandler("/" + fileUploadPath + "/**") + .addResourceLocations("file:" + fileUploadRootPath + fileUploadPath); + } + + @Bean + public WebInterceptor webInterceptor() { + return new WebInterceptor(); + } +} diff --git a/src/main/java/com/fxzy/warn/common/conf/WebInterceptor.java b/src/main/java/com/fxzy/warn/common/conf/WebInterceptor.java new file mode 100644 index 0000000..b9091f6 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/conf/WebInterceptor.java @@ -0,0 +1,90 @@ +package com.fxzy.warn.common.conf; + +import com.alibaba.fastjson.JSONObject; + +import com.fxzy.warn.common.constants.RedisKeyConstants; +import com.fxzy.warn.common.constants.ResponseMsgConstants; +import com.fxzy.warn.common.response.ApiResponse; +import com.fxzy.warn.common.util.RedisUtil; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +/** + * 拦截器 + * + * @author yuyantian + * @date 2021/09/07 14:30 + */ +public class WebInterceptor implements HandlerInterceptor { + @Autowired + public RedisUtil redisUtil; + + + private static final Logger logger = LoggerFactory.getLogger(WebInterceptor.class); + + + private void returnError(HttpServletRequest request, HttpServletResponse response) { + response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); + try (PrintWriter writer = response.getWriter()) { + ApiResponse apiResponse = new ApiResponse(); + apiResponse.setCode(ResponseMsgConstants.FAIL_CODE_401); + apiResponse.setMessage("ticket无效,请重新登录后操作"); + writer.print(JSONObject.toJSONString(apiResponse)); + } catch (IOException e) { + logger.error("web拦截器异常", e); + } + } + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, + Object handler) throws Exception { + + try { + logger.debug("请求:{}", request.getRequestURL()); + //校验ticket是否有效 + String ticket = request.getHeader("ticket"); + //如果header中不存在ticket,则从参数中获取ticket + if (StringUtils.isBlank(ticket)) { + ticket = request.getParameter("ticket"); + } + + if (redisUtil.exists(RedisKeyConstants.LOGIN_ST + ticket)) { + return true; + } else { + returnError(request, response); + } + return true; + } catch (Exception e) { + logger.error("web拦截器异常", e); + returnError(request, response); + return false; + } + } + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object + handler, + ModelAndView modelAndView) throws Exception { + // TODO Auto-generated method stub + + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, + Object handler, Exception ex) + throws Exception { + // TODO Auto-generated method stub + + } + +} diff --git a/src/main/java/com/fxzy/warn/common/constants/EntityConstants.java b/src/main/java/com/fxzy/warn/common/constants/EntityConstants.java new file mode 100644 index 0000000..034625c --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/constants/EntityConstants.java @@ -0,0 +1,37 @@ +package com.fxzy.warn.common.constants; + +import lombok.Builder; + +/** + * model参数常量常量 + * + * @author yuyantian + * @date + */ +public class EntityConstants { + + /** + * 删除状态(0-正常状态,1删除状态) + */ + public final static Integer NORMAL = 0; + public final static Integer DEL = 1; + + /** + * 此处为冯海磊设置的常量 + * 为状态量时 (0-正常,1-停用) + * 为is开头的是否值时 (0-是,1-否) + */ + public final static Integer HL_YES = 0; + public final static Integer HL_NO = 1; + + + + /** + * 用户类型:0:默认 1:市级;2:区县;3:企业,4:群众 + */ + public final static Integer USER_TYPE_DEFAULT = 0; + public final static Integer USER_TYPE_CITY = 1; + public final static Integer USER_TYPE_AREA = 2; + public final static Integer USER_TYPE_UNIT = 3; + public final static Integer USER_TYPE_PUBLIC = 4; +} diff --git a/src/main/java/com/fxzy/warn/common/constants/LawResearchUrlConstants.java b/src/main/java/com/fxzy/warn/common/constants/LawResearchUrlConstants.java new file mode 100644 index 0000000..9b04633 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/constants/LawResearchUrlConstants.java @@ -0,0 +1,90 @@ +package com.fxzy.warn.common.constants; + +/** + * @author zhangjing + * @date 2024/09/19 09:39 + * @description + */ +public class LawResearchUrlConstants { + + //----------------正式------------ +// static final String BASE_URL = "https://qyss.cjbdi.com/qyss"; + //加密密钥 +// String key = "QOczcxT@EtdGsoqc"; + //接口调用凭证 +// String ticket = "sWLi80ouoxiK9jYJFti2j43Cgzpxf2CSmE5/8qj5jsTpVmXwH4sjsrlpwh882FR9vjXFDOzWS2s5+P72GwY0Xg=="; + + + //-----------------测试------------- + public final static String BASE_URL = "http://123.124.130.19/qysstest"; + //加密密钥 + public final static String KEY = "COtP3DH$Pcw2ccs1"; + //接口调用凭证 + public final static String TICKET = "sWLi80ouoxiK9jYJFti2jz9KWnUtRvdepXf4jOWAwgyfSy4Kkf+n6yux/IuhFrL/"; + + + //司法 + public final static String QUERY_SSSXXG ="/qyss/sfss/querySssxxg"; + //工商 + public final static String QUERY_ENT_INFO = "/qyss/cr/queryEntInfo"; + //工商工商基础信 + public final static String COMPANY_ENTINFO = "/qyss/company/entInfo"; + //制裁实体详情接口 + public final static String SANCTION_NAME = "/qyss/sanction/info/name"; + //一般纳税人 + public final static String GENERAL_TAXPAYER = "/qyss/fyss/generalTaxpayer"; + //股权图谱接口 + public final static String ATLAS = "/qyss/sf/invest/external/atlas"; + //关联人物图谱接口 + public final static String RISK_COMPANY = "/qyss/sf/legal/correlation/risk/company"; + //企业司法画像-债权债务趋势图接口 + public final static String CASE_TREND_MAP = "/qyss/sf/esbasicdata/company/caseTrendMap"; + //企业司法画像-审理程序分布接口 + public final static String GET_CASE_TREND_MAP = "/qyss/sf/esbasicdata/investigate/getCaseAnalysisInfo"; + //企业司法画像-诉讼地位分布接口 + public final static String GET_CASE_SSDW_INFO = "/qyss/sf/esbasicdata/investigate/getCaseSsdwInfo"; + //企业司法画像-主诉/被诉诉讼结果接口 + public final static String GET_CASE_SSJG_INFO = "/qyss/sf/esbasicdata/investigate/getCaseSsjgInfo"; + //企业司法画像-案件走势图接口 + public final static String COUNT_ALL_CASE_NUMBER = "/qyss/sf/esbasicdata/investigate/company/getCountAllCaseNumber"; + //企业司法画像-涉诉关系图接口 + public final static String LITIGATION_RELATIONSHIP = "/qyss/sf/esbasicdata/investigate/litigationRelationship"; + //企业司法画像-涉诉标的额接口 + public final static String COUNT_CASE_LITIGATION = "/qyss/sf/esbasicdata/investigate/company/countCaseLitigationAmountAll"; + //企业司法画像-地域分布图接口 + public final static String COUNT_CASE_PROVINCE = "/qyss/sf/esbasicdata/company/countCaseProvince"; + //企业司法画像-案由分布图接口 + public final static String COUNT_SUMMARY = "/qyss/sf/esbasicdata/company/countSummary"; + //投融资风险审查接口 + public final static String RISK_REVIEW = "/qyss/sf/investFinance/riskReview"; + //投融资风险详情接口 + public final static String RISK_REVIEW_PAGE_INFO = "/qyss/sf/investFinance/riskReview/pageInfo"; + //投融资风险详情接口 + public final static String OVERVIEW = "/qyss/sf/contractRisk/overview"; + //合同履约风险列表接口 + public final static String OVERVIEW_PAGE_INFO = "/qyss/sf/contractRisk/overview/pageInfo"; + //监控名单添加接口 + public final static String ADD_PUBLIC = "/qyss/monitor/addpublic"; + //监控名单删除接口 + public final static String DEL_COMPANY = "/qyss/monitor/delcompany"; + //监控名单查询接口 + public final static String MONITOR_QUERY = "/qyss/monitor/query"; + //监控信息获取 + public final static String QUERY_MONITOR_CASES = "/qyss/dsk/queryMonitorCases"; + //不良记录审查结果接口 + public final static String BADRECORD = "/qyss/risk/badrecord"; + //类案诉讼实体接口 + public final static String LIST_BY_ENTERPRISE = "/wenshu/queryws/listByEnterprise"; + //类案详情查询接口 + public final static String QUERY_WS_SHOW_BY_ID = "/wenshu/queryws/showById"; + //类案详情列表接口 + public final static String QUERY_WS_DETAILS_LIST = "/wenshu/queryws/detailsList"; + //获取文书接口 + public final static String QUERYWS = "/wenshu/queryws/id"; + //专利查询列表接口 + public final static String ZL_QUERY = "/qyss/zl/query"; + //专利查询列表接口 + public final static String ZL_DETAILS = "/qyss/zl/queryZLDetails"; + + +} diff --git a/src/main/java/com/fxzy/warn/common/constants/RedisKeyConstants.java b/src/main/java/com/fxzy/warn/common/constants/RedisKeyConstants.java new file mode 100644 index 0000000..9640bfc --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/constants/RedisKeyConstants.java @@ -0,0 +1,28 @@ +package com.fxzy.warn.common.constants; + +/** + * model参数常量常量 + * + * @author yuyantian + * @date + */ +public class RedisKeyConstants { + + /**用户是否锁定key*/ + public final static String USER_LOCK_KEY = "gas_apportal:user:lock:"; + + /**登录ST*/ + public final static String LOGIN_ST = "gas_wx:login:st:"; + + public final static String LOGIN_ST_HEADER = "ST-"; + + /**登录随机数验证码*/ + public final static String LOGIN_RANDOM_CAPTCHA = "gas_apportal:login:random:captcha-"; + + /**登录随机数验证码图片类型*/ + public final static String LOGIN_RANDOM_CAPTCHA_IMG_TYPE = ".jpg"; + + + + +} diff --git a/src/main/java/com/fxzy/warn/common/constants/ResponseMsgConstants.java b/src/main/java/com/fxzy/warn/common/constants/ResponseMsgConstants.java new file mode 100644 index 0000000..c6ae15d --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/constants/ResponseMsgConstants.java @@ -0,0 +1,45 @@ +package com.fxzy.warn.common.constants; + +/** + * 返回信息常量 + * + * @author yuyantian + * @date + */ +public class ResponseMsgConstants { + /** + * 操作成功 + */ + public final static Integer SUCCESS_CODE_200 = 200; + /** + * 登录失效 + */ + public final static Integer FAIL_CODE_401 = 401; + /** + * 操作失败 + */ + public final static Integer FAIL_CODE_500 = 500; + /** + * 操作失败 + */ + public final static Integer FAIL_CODE_501 = 501; + + + public final static String OPERATE_SUCCESS = "操作成功"; + + public final static String OPERATE_FAIL = "操作失败"; + + + public final static String OPERATE_SYS_ERROR = "系统异常"; + + public final static String OPERATE_NAME_REPEAT = "名称不能重复"; + + public final static String OPERATE_UNDELETE = "不能删除该类型"; + + public final static String OPEARTE_DICT_DICTCODE_REPEAT = "数据字典编码不能重复"; + + public final static String OPEARTE_DICTITEM_DICTCODE_REPEAT = "数据字典项编码不能重复"; + + public final static String UN_ERROR = "未知"; + +} diff --git a/src/main/java/com/fxzy/warn/common/filter/CrossDomainFilter.java b/src/main/java/com/fxzy/warn/common/filter/CrossDomainFilter.java new file mode 100644 index 0000000..0c280d8 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/filter/CrossDomainFilter.java @@ -0,0 +1,57 @@ +package com.fxzy.warn.common.filter; + +import org.slf4j.MDC; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 跨域过滤器 + * + * @author yuyantian + * @data 2021/9/7 14:30 + */ +@Order(0) +@Component +public class CrossDomainFilter implements Filter { + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + private final AtomicInteger traceIdCounter = new AtomicInteger(10000); + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, + FilterChain filterChain) throws IOException, ServletException { + HttpServletResponse response = (HttpServletResponse) servletResponse; + HttpServletRequest request = (HttpServletRequest) servletRequest; + + response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); + response.setHeader("Access-Control-Allow-Headers", + "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,openId,authorization,Content-Disposition"); + response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); + response.setHeader("Access-Control-Max-Age", "0"); + response.addHeader("Access-Control-Allow-Credentials", "true"); + response.addHeader("Access-Control-Expose-Headers", "Content-Disposition"); + response.setHeader("contentType", "application/json; charset=utf-8"); + response.setCharacterEncoding("utf-8"); + try { + // logback 文件日志 traceId, 让同一请求下的日志 traceId 相同 + MDC.put("traceId", String.valueOf(traceIdCounter.getAndIncrement())); + filterChain.doFilter(request, response); + } finally { + MDC.remove("traceId"); + } + } + + @Override + public void destroy() { + + } +} diff --git a/src/main/java/com/fxzy/warn/common/filter/XssFilter.java b/src/main/java/com/fxzy/warn/common/filter/XssFilter.java new file mode 100644 index 0000000..9a3f7e1 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/filter/XssFilter.java @@ -0,0 +1,32 @@ +package com.fxzy.warn.common.filter; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +/** + * XSS过滤 + * + * @author yuyantian + * @date 2021/9/7 14:30 + */ +public class XssFilter implements Filter { + + FilterConfig filterConfig = null; + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + this.filterConfig = filterConfig; + } + + @Override + public void destroy() { + this.filterConfig = null; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response); + } +} diff --git a/src/main/java/com/fxzy/warn/common/filter/XssHttpServletRequestWrapper.java b/src/main/java/com/fxzy/warn/common/filter/XssHttpServletRequestWrapper.java new file mode 100644 index 0000000..7b9843d --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/filter/XssHttpServletRequestWrapper.java @@ -0,0 +1,125 @@ +package com.fxzy.warn.common.filter; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; + +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * XSS过滤配置 + * + * @author yuyantian + * @date 2021/9/7 14:30 + */ +public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { + + public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) { + super(servletRequest); + } + + @Override + public ServletInputStream getInputStream() throws IOException { + //非json类型,直接返回 + if (!MediaType.APPLICATION_JSON_VALUE + .equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))) { + return super.getInputStream(); + } + + //为空,直接返回 + String json = IOUtils.toString(super.getInputStream(), "utf-8"); + if (StringUtils.isBlank(json)) { + return super.getInputStream(); + } + + //xss过滤 + json = cleanXSS(json); + final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8")); + return new ServletInputStream() { + @Override + public boolean isFinished() { + return true; + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setReadListener(ReadListener readListener) { + } + + @Override + public int read() throws IOException { + return bis.read(); + } + }; + } + + @Override + public String[] getParameterValues(String parameter) { + String[] values = super.getParameterValues(parameter); + if (values == null) { + return null; + } + int count = values.length; + String[] encodedValues = new String[count]; + for (int i = 0; i < count; i++) { + encodedValues[i] = cleanXSS(values[i]); + } + return encodedValues; + } + + @Override + public String getParameter(String parameter) { + String value = super.getParameter(parameter); + if (value == null) { + return null; + } + return cleanXSS(value); + } + + @Override + public Map getParameterMap() { + Map map = new LinkedHashMap<>(); + Map parameters = super.getParameterMap(); + for (String key : parameters.keySet()) { + String[] values = parameters.get(key); + for (int i = 0; i < values.length; i++) { + values[i] = cleanXSS(values[i]); + } + map.put(key, values); + } + return map; + } + + @Override + public String getHeader(String name) { + String value = super.getHeader(name); + if (value == null) { + return null; + } + return cleanXSS(value); + } + + private String cleanXSS(String value) { + //You'll need to remove the spaces from the html entities below + value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;"); + value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;"); + value = value.replaceAll("'", "& #39;"); + value = value.replaceAll("eval\\((.*)\\)", ""); + value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); + value = value.replaceAll("(?i)script", ""); + return value; + } + +} diff --git a/src/main/java/com/fxzy/warn/common/request/RequestParameter.java b/src/main/java/com/fxzy/warn/common/request/RequestParameter.java new file mode 100644 index 0000000..b683fc2 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/request/RequestParameter.java @@ -0,0 +1,67 @@ +package com.fxzy.warn.common.request; + +import com.alibaba.fastjson.JSONObject; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; + + +/** + * 请求类 + * + * @author yuyantian + * @date 2021/09/07 14:30 + */ +@ApiModel(value = "请求类") +public class RequestParameter implements Serializable { + + private static final long serialVersionUID = 1244437270503922868L; + + @ApiModelProperty(value = "实体参数") + private JSONObject parameter = new JSONObject(); + + /** + * 每页数据条数 + */ + @ApiModelProperty(value = "分页条件") + private int size; + /** + * 当前页面 + */ + @ApiModelProperty(value = "每页个数") + private int current; + + public RequestParameter() { + this.current = 1; + this.size = 10; + } + + public JSONObject getParameter() { + return parameter; + } + + public void setParameter(JSONObject parameter) { + this.parameter = parameter; + } + + public int getCurrent() { + return current; + } + + public void setCurrent(int current) { + this.current = current; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + + public void setParameter() { + } +} diff --git a/src/main/java/com/fxzy/warn/common/response/ApiResponse.java b/src/main/java/com/fxzy/warn/common/response/ApiResponse.java new file mode 100644 index 0000000..e86316e --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/response/ApiResponse.java @@ -0,0 +1,90 @@ +package com.fxzy.warn.common.response; + +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; + +/** + * 请求返回对象 + * + * @author yuyantian + * @date 2021/09/07 14:30 + */ + +public class ApiResponse implements Serializable { + + private static final long serialVersionUID = 6459579728006690174L; + + /** + * 状态码 + */ + @ApiModelProperty("状态码") + private int code; + + /** + * 错误原因 + */ + @ApiModelProperty("错误原因") + private String message; + + /** + * 返回结果 + */ + @ApiModelProperty("返回结果") + private Object data; + + + public ApiResponse() { + this.code = 200; + this.message = "操作成功"; + } + + public ApiResponse(Object data) { + new ApiResponse(); + this.code = 200; + this.data = data; + } + + public void recordError(int code) { + this.code = code; + this.message = StatusCode.getStatusCode(code).getMessage(); + } + + public void recordError(String error) { + this.code = 500; + this.message = error; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + @Override + public String toString() { + return "ApiResponse{" + + "code='" + code + '\'' + + ", message='" + message + '\'' + + ", data=" + data + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/fxzy/warn/common/response/ApiResponseT.java b/src/main/java/com/fxzy/warn/common/response/ApiResponseT.java new file mode 100644 index 0000000..766f08e --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/response/ApiResponseT.java @@ -0,0 +1,90 @@ +package com.fxzy.warn.common.response; + +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; + +/** + * 请求返回对象 + * + * @author yuyantian + * @date 2021/09/07 14:30 + */ + +public class ApiResponseT implements Serializable { + + private static final long serialVersionUID = 6459579728006690174L; + + /** + * 状态码 + */ + @ApiModelProperty("状态码") + private int code; + + /** + * 错误原因 + */ + @ApiModelProperty("错误原因") + private String message; + + /** + * 返回结果 + */ + @ApiModelProperty("返回结果") + private T data; + + + public ApiResponseT() { + this.code = 200; + this.message = "操作成功"; + } + + public ApiResponseT(T data) { + new ApiResponseT(); + this.code = 200; + this.data = data; + } + + public void recordError(int code) { + this.code = code; + this.message = StatusCode.getStatusCode(code).getMessage(); + } + + public void recordError(String error) { + this.code = 500; + this.message = error; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + @Override + public String toString() { + return "ApiResponse{" + + "code='" + code + '\'' + + ", message='" + message + '\'' + + ", data=" + data + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/fxzy/warn/common/response/StatusCode.java b/src/main/java/com/fxzy/warn/common/response/StatusCode.java new file mode 100644 index 0000000..ad2a3ba --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/response/StatusCode.java @@ -0,0 +1,82 @@ +package com.fxzy.warn.common.response; + + +import org.springframework.core.io.ClassPathResource; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; + +/** + * 状态码 + * + * @author yuyantian + * @date 2019/11/16 + */ +public class StatusCode { + + + private static Map statusCodes = new HashMap<>(); + + static { + statusCodes.put(200, new StatusCode(200, "操作成功")); + statusCodes.put(500, new StatusCode(500, "操作失败")); + InputStreamReader in = null; + try { + ClassPathResource resource = new ClassPathResource("/errorCode.properties"); + in = new InputStreamReader(resource.getInputStream(), "GBK"); + Properties properties = new Properties(); + properties.load(in); + Set propertyNames = properties.stringPropertyNames(); + Iterator iterator = propertyNames.iterator(); + while (iterator.hasNext()) { + String code = iterator.next(); + Integer intCode = Integer.valueOf(code); + statusCodes.put(intCode, new StatusCode(intCode, properties.getProperty(code))); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + private int code; + + private String message; + + public static StatusCode getStatusCode(int code) { + return statusCodes.get(code); + } + + private StatusCode() { + + } + + public StatusCode(int code, String message) { + this.code = code; + this.message = message; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/src/main/java/com/fxzy/warn/common/util/AES.java b/src/main/java/com/fxzy/warn/common/util/AES.java new file mode 100644 index 0000000..92797bf --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/util/AES.java @@ -0,0 +1,107 @@ +package com.fxzy.warn.common.util; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang.StringUtils; +import sun.misc.BASE64Decoder; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.spec.SecretKeySpec; + +/** + * @author zhangjing + * @date 2024/08/06 14:34 + * @description + */ +public class AES { + //密钥 (需要前端和后端保持一致) + private static final String KEY = "1234567890ABCDEf"; + //算法 + private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding"; + + /** + * base 64 encode + * + * @param bytes 待编码的 byte[] + * @return 编码后的 base 64 code + */ + public static String base64Encode(byte[] bytes) { + return Base64.encodeBase64String(bytes); + } + + /** + * base 64 decode + * + * @param base64Code + * @return byte[] + * @author zhangjing + * @create 2024/8/6 + **/ + public static byte[] base64Decode(String base64Code) throws Exception { + return StringUtils.isNotEmpty(base64Code) ? new + BASE64Decoder().decodeBuffer(base64Code) : null; + } + + /** + * AES 加密 + * + * @param content 待加密的内容 + * @param encryptKey 加密密钥 + * @return 加密后的 byte[] + * @throws Exception + */ + public static byte[] aesEncryptToBytes(String content, String encryptKey) + throws Exception { + KeyGenerator kgen = KeyGenerator.getInstance("AES"); + kgen.init(128); + Cipher cipher = Cipher.getInstance(ALGORITHMSTR); + cipher.init(Cipher.ENCRYPT_MODE, new + SecretKeySpec(encryptKey.getBytes(), "AES")); + return cipher.doFinal(content.getBytes("utf-8")); + } + /** + * AES 加密为 base 64 code + * + * @param content 待加密的内容 + * @param encryptKey 加密密钥 + * @return 加密后的 base 64 code + * @throws Exception + */ + public static String aesEncrypt(String content, String encryptKey) throws + Exception { + return base64Encode(aesEncryptToBytes(content, encryptKey)); + } + + /** + * AES 解密 + * + * @param encryptBytes 待解密的 byte[] + * @param decryptKey 解密密钥 + * @return 解密后的 String + * @throws Exception + */ + public static String aesDecryptByBytes(byte[] encryptBytes, String + decryptKey) throws Exception { + KeyGenerator kgen = KeyGenerator.getInstance("AES"); + kgen.init(128); + Cipher cipher = Cipher.getInstance(ALGORITHMSTR); + cipher.init(Cipher.DECRYPT_MODE, new + SecretKeySpec(decryptKey.getBytes(), "AES")); + byte[] decryptBytes = cipher.doFinal(encryptBytes); + return new String(decryptBytes); + } + + /** + * 将 base 64 code AES 解密 + * + * @param encryptStr 待解密的 base 64 code + * @param decryptKey 解密密钥 + * @return 解密后的 string + * @throws Exception + */ + public static String aesDecrypt(String encryptStr, String decryptKey) throws + Exception { + return StringUtils.isNotEmpty(encryptStr) ? + aesDecryptByBytes(base64Decode(encryptStr), decryptKey) : null; + } +} diff --git a/src/main/java/com/fxzy/warn/common/util/Demo.java b/src/main/java/com/fxzy/warn/common/util/Demo.java new file mode 100644 index 0000000..191536b --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/util/Demo.java @@ -0,0 +1,28 @@ +package com.fxzy.warn.common.util; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import org.apache.http.HttpResponse; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ByteArrayEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.springframework.http.*; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; + +/** + * @author zhangjing + * @date 2024/08/06 14:42 + * @description + */ +public class Demo { + public static void main(String[] args) { + LawResearchUtil law = new LawResearchUtil(); + law.queryEntInfo(null, null); + } +} diff --git a/src/main/java/com/fxzy/warn/common/util/FileUtil.java b/src/main/java/com/fxzy/warn/common/util/FileUtil.java new file mode 100644 index 0000000..94ee43b --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/util/FileUtil.java @@ -0,0 +1,454 @@ +package com.fxzy.warn.common.util; + +import lombok.extern.log4j.Log4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; + +import javax.imageio.stream.FileImageOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author yuyantian + * @date 2020/8/19 + */ +@Log4j +@Component +public class FileUtil { + + public void downloadTemplate(File file, String templatePath, String fileName, + HttpServletRequest request, HttpServletResponse response) { + BufferedInputStream bis; + try { + Map result = setResponseHeader(fileName, file.length(), request, response); + long rangeSwitch = result.get("rangeSwitch"); + long from = result.get("from"); + long contentLength = result.get("contentLength"); + + InputStream ins = getClass().getClassLoader() + .getResourceAsStream(templatePath); + bis = new BufferedInputStream(ins); + + // 输出流 + bis.skip(from); + OutputStream out = response.getOutputStream(); + int read; + long readLength = 0; + int bufferSize = 1024; + byte[] buffer = new byte[bufferSize]; + if (rangeSwitch == 2) { + // 写区间 + while (readLength <= contentLength - bufferSize) { + read = bis.read(buffer); + readLength += read; + out.write(buffer, 0, read); + } + if (readLength < contentLength) { + read = bis.read(buffer, 0, (int) (contentLength - readLength)); + out.write(buffer, 0, read); + } + } else { + // 写(余下)全部 + while ((read = bis.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + } + out.flush(); + out.close(); + bis.close(); + } catch (IOException e) { + log.warn("下载文件发生错误" + e.getMessage()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void saveAsFileWriter(String content, String filePath) { + try ( + // true表示不覆盖原来的内容,而是加到文件的后面。若要覆盖原来的内容,直接省略这个参数就好 + FileOutputStream fos = new FileOutputStream(filePath, true); + OutputStreamWriter writer = new OutputStreamWriter(fos, StandardCharsets.UTF_8); + ) { + writer.write(content); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static boolean writeBytes(File file, String fileName, HttpServletRequest request, + HttpServletResponse response) { + BufferedInputStream bis; + boolean downloadSuccess = false; + try { + Map result = setResponseHeader(fileName, file.length(), request, response); + long rangeSwitch = result.get("rangeSwitch"); + long from = result.get("from"); + long contentLength = result.get("contentLength"); + + InputStream ins = new FileInputStream(file); + bis = new BufferedInputStream(ins); + + // 输出流 + bis.skip(from); + OutputStream out = response.getOutputStream(); + int read; + long readLength = 0; + int bufferSize = 1024; + byte[] buffer = new byte[bufferSize]; + if (rangeSwitch == 2) { + // 写区间 + while (readLength <= contentLength - bufferSize) { + read = bis.read(buffer); + readLength += read; + out.write(buffer, 0, read); + } + if (readLength < contentLength) { + read = bis.read(buffer, 0, (int) (contentLength - readLength)); + out.write(buffer, 0, read); + } + } else { + // 写(余下)全部 + while ((read = bis.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + } + out.flush(); + out.close(); + bis.close(); + downloadSuccess = true; + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + downloadSuccess = false; + log.warn("下载文件发生错误" + e.getMessage()); + } catch (Exception e) { + e.printStackTrace(); + downloadSuccess = false; + } + return downloadSuccess; + } + + + private static Map setResponseHeader(String fileName, long totalSize, + HttpServletRequest request, HttpServletResponse response) { + Map result = new HashMap(); + long rangeSwitch = 0; + long contentLength; + long from = 0; + long to = totalSize - 1; + + String range = request.getHeader("Range"); + if (StringUtils.isNotBlank(range)) { + response.setStatus(206); + String rangBytes = range.split("=")[1]; + int splitIndex = rangBytes.indexOf("-"); + if (rangBytes.endsWith("-")) { // bytes=from-, 单线程断点续传 + rangeSwitch = 1; + from = Long.valueOf(rangBytes.substring(0, splitIndex)); + } else { // bytes=from-to, 多线程下载 + rangeSwitch = 2; + from = Long.valueOf(rangBytes.substring(0, splitIndex)); + to = Long.valueOf(rangBytes.substring(splitIndex + 1)); + } + } + + contentLength = to - from + 1; + + response.setHeader("Accept-Ranges", "bytes"); + response.setHeader("Content-Length", String.valueOf(contentLength)); + // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小] + response.setHeader("Content-Range", + rangeSwitch == 2 ? (range.replace("=", " ") + "/" + totalSize) : ("bytes " + + from + "-" + to + "/" + totalSize)); + response.setContentType("application/octet-stream"); + try { + response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder + .encode(fileName, "UTF-8")); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + result.put("rangeSwitch", rangeSwitch); + result.put("contentLength", contentLength); + result.put("from", from); + result.put("to", to); + + return result; + } + + + /** + * 创建文件夹 + */ + public static void createDir(String path) { + File file = new File(path); + if (!file.exists()) { + file.mkdirs(); + } + } + + + /** + * 上传 + * + * @param multipartFile 文件 + * @param saveFilePath 存储路径 + */ + public static boolean upload(MultipartFile multipartFile, String saveFilePath) { + boolean result = false; + if (null == multipartFile || StringUtils.isBlank(saveFilePath)) { + return result; + } + File file = new File(saveFilePath); + try { + multipartFile.transferTo(file); + result = true; + } catch (IOException e) { + e.printStackTrace(); + } + return result; + } + + /** + * 合并指定目录下的所有 文件 + */ + public static void combineFiles(List files, String dirPath, String saveFileName) + throws IOException { + + if (files == null || files.size() < 1) { + throw new RuntimeException("待合并的文件不存在..."); + } + + File outputFile = new File(dirPath + File.separator + saveFileName); + + if (!outputFile.exists()) { + outputFile.createNewFile(); + } + // 根据文件chunk排序 + Map nameChunkMap = new HashMap<>(); + for (File f : files) { + String name = f.getName(); + nameChunkMap.put(name, + Integer.valueOf(name.substring(name.lastIndexOf('_') + 1, name.lastIndexOf(".tmp")))); + } + files.sort((f1, f2) -> { + return nameChunkMap.get(f1.getName()) - nameChunkMap.get(f2.getName()); + }); + + FileChannel outChannel = new FileOutputStream(outputFile).getChannel(); + FileChannel inChannel; + for (File file : files) { + inChannel = new FileInputStream(file).getChannel(); + inChannel.transferTo(0, inChannel.size(), outChannel); + + inChannel.close(); + } + outChannel.close(); + } + + /** + * 删除文件夹及文件夹下的所有文件 + */ + public static void deleteDir(String dirPath) { + File file = new File(dirPath); + if (file.isFile()) { + file.delete(); + } else { + File[] files = file.listFiles(); + if (files == null) { + file.delete(); + } else { + for (int i = 0; i < files.length; i++) { + deleteDir(files[i].getAbsolutePath()); + } + file.delete(); + } + } + } + + /** + * 流的方式下载 + */ + public static void writesToFlow(File file, String fileName, HttpServletRequest request, + HttpServletResponse response) throws IOException { + setResponseHeader(fileName, file.length(), request, response); + //读取路径下面的文件 + //读取指定路径下面的文件 + InputStream in = new FileInputStream(file); + OutputStream outputStream = response.getOutputStream(); + //创建存放文件内容的数组 + byte[] buff = new byte[1024]; + //所读取的内容使用n来接收 + int n; + //当没有读取完时,继续读取,循环 + while ((n = in.read(buff)) != -1) { + //将字节数组的数据全部写入到输出流中 + outputStream.write(buff, 0, n); + } + //强制将缓存区的数据进行输出 + outputStream.flush(); + //关流 + outputStream.close(); + in.close(); + } + + + /** + * 设置响应参数 + */ + private static OutputStream setDownloadOutputStream(HttpServletResponse response, String fileName, + String fileType) throws IOException { + + fileName = new String(fileName.getBytes(), "ISO-8859-1"); + response.setHeader("Content-Disposition", "attachment;filename=" + fileName + "." + fileType); + response.setContentType("multipart/form-data"); + return response.getOutputStream(); + + } + + /** + * 将byte[]类型的数据,写入到输出流中 + * + * @param out 输出流 + * @param data 希望写入的数据 + * @param cacheSize 写入数据是循环读取写入的,此为每次读取的大小,单位字节,建议为4096,即4k + */ + private static void writeBytesToOut(OutputStream out, byte[] data, int cacheSize) + throws IOException { + int surplus = data.length % cacheSize; + int count = surplus == 0 ? data.length / cacheSize : data.length / cacheSize + 1; + + for (int i = 0; i < count; i++) { + if (i == count - 1 && surplus != 0) { + out.write(data, i * cacheSize, surplus); + continue; + } + out.write(data, i * cacheSize, cacheSize); + } + } + + /** + * 获得指定文件的byte数组 + */ + private static byte[] getBytes(String filePath) { + byte[] buffer = null; + try { + File file = new File(filePath); + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); + byte[] b = new byte[1000]; + int n; + while ((n = fis.read(b)) != -1) { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return buffer; + } + + + /** + * 获取文件类型 + */ + public static String getFileType(String fileName) { + if (StringUtils.isNotBlank(fileName) && fileName.indexOf(".") > 0) { + return fileName.substring(fileName.lastIndexOf(".")); + } + return null; + } + + /** + * 将InputStream写入本地文件 + * + * @param destination 写入本地目录 + * @param input 输入流 + */ + public static void writeToLocal(String destination, InputStream input) + throws IOException { + int index; + byte[] bytes = new byte[1024]; + FileOutputStream downloadFile = new FileOutputStream(destination); + while ((index = input.read(bytes)) != -1) { + downloadFile.write(bytes, 0, index); + downloadFile.flush(); + } + downloadFile.close(); + input.close(); + } + + public void byte2image(byte[] data, String path) { + if (data.length < 3 || path.equals("")) { + return;//判断输入的byte是否为空 + } + try { + FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));//打开输入流 + imageOutput.write(data, 0, data.length);//将byte写入硬盘 + imageOutput.close(); + System.out.println("Make Picture success,Please find image in " + path); + } catch (Exception ex) { + System.out.println("Exception: " + ex); + ex.printStackTrace(); + } + } + + /** + * 读取网络文件 + */ + public byte[] openFile(String filePath) { + int HttpResult; // 服务器返回的状态 + ByteArrayOutputStream bos; + byte[] var7 = new byte[0]; + BufferedInputStream in = null; + try { + URL url = new URL(filePath); // 创建URL + URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码 + urlconn.connect(); + HttpURLConnection httpconn = (HttpURLConnection) urlconn; + HttpResult = httpconn.getResponseCode(); + if (HttpResult != HttpURLConnection.HTTP_OK) { + throw new IOException("无法连接到网络文件服务器!"); + } else { + int filesize = urlconn.getContentLength(); + bos = new ByteArrayOutputStream(filesize); + in = new BufferedInputStream(urlconn.getInputStream()); + short bufSize = 1024; + byte[] buffer = new byte[bufSize]; + int len1; + while (-1 != (len1 = in.read(buffer, 0, bufSize))) { + bos.write(buffer, 0, len1); + } + var7 = bos.toByteArray(); + return var7; + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally{ + try { + if (in != null) { + in.close(); + } + } catch (IOException var14) { + var14.printStackTrace(); + } + } + return var7; + } +} \ No newline at end of file diff --git a/src/main/java/com/fxzy/warn/common/util/HttpUtil.java b/src/main/java/com/fxzy/warn/common/util/HttpUtil.java new file mode 100644 index 0000000..0a62194 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/util/HttpUtil.java @@ -0,0 +1,198 @@ +package com.fxzy.warn.common.util; + +import com.alibaba.fastjson.JSONObject; +import org.apache.http.HttpEntity; +import org.apache.http.HttpStatus; +import org.apache.http.StatusLine; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * http工具类 + * + * @author yuyantian + * @date 2020/05/14 + */ +public class HttpUtil { + + + /** + * Get请求 + */ + public static String doGet(String url) { + String result = null; + CloseableHttpClient httpclient = HttpClients.createDefault(); + HttpClientContext context = HttpClientContext.create(); + try { + HttpGet httpget = new HttpGet(url); + RequestConfig defaultRequestConfig = RequestConfig.custom() + .setSocketTimeout(10000) + .setConnectTimeout(10000) + .setConnectionRequestTimeout(10000) + .build(); + httpget.setConfig(defaultRequestConfig); + System.out.println("executing request " + httpget.getURI()); + // 执行get请求. + CloseableHttpResponse response = httpclient.execute(httpget, context); + // 获取响应实体 + HttpEntity entity = response.getEntity(); + if (entity != null) { + result = EntityUtils.toString(entity, "UTF-8"); + } + + } catch (IOException e) { + System.out.println("http请求失败,url:" + url); + e.printStackTrace(); + } finally { + // 关闭连接,释放资源 + try { + httpclient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + } + + /** + * Post请求 + */ + public static String doPost(String openId,String url, String params) throws Exception { + + CloseableHttpClient httpclient = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(url);// 创建httpPost + httpPost.setHeader("Accept", "application/json"); + httpPost.setHeader("Content-Type", "application/json"); + httpPost.setHeader("openId", openId); + RequestConfig defaultRequestConfig = RequestConfig.custom() + .setSocketTimeout(10000) + .setConnectTimeout(10000) + .setConnectionRequestTimeout(10000) + .build(); + httpPost.setConfig(defaultRequestConfig); + String charSet = "UTF-8"; + StringEntity entity = new StringEntity(params, charSet); + httpPost.setEntity(entity); + CloseableHttpResponse response = null; + HttpClientContext context = HttpClientContext.create(); + try { + + response = httpclient.execute(httpPost, context); + StatusLine status = response.getStatusLine(); + int state = status.getStatusCode(); + if (state == HttpStatus.SC_OK) { + HttpEntity responseEntity = response.getEntity(); + String jsonString = EntityUtils.toString(responseEntity); + return jsonString; + } else { + //do log + } + } finally { + if (response != null) { + try { + response.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + try { + httpclient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } + + /** + * post请求 + * + * @return json格式对象 + */ + public static JSONObject sendPostRequest(String url) { + JSONObject resultJson = null; + StringBuffer stringBuffer = new StringBuffer(""); + try { + URL postUrl = new URL(url); + HttpURLConnection connection = (HttpURLConnection) postUrl + .openConnection(); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setRequestMethod("POST"); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(true); + connection.setRequestProperty("Content-Type", "application/json"); + BufferedReader reader = new BufferedReader(new InputStreamReader( + connection.getInputStream())); + String line; + while ((line = reader.readLine()) != null) { + stringBuffer.append(line); + } + reader.close(); + resultJson = JSONObject.parseObject(stringBuffer.toString()); + } catch (Exception e) { + e.printStackTrace(); + } + + return resultJson; + } + + public static String doPost(String url, String params) throws Exception { + + CloseableHttpClient httpclient = HttpClients.createDefault(); + HttpPost httpPost = new HttpPost(url);// 创建httpPost + httpPost.setHeader("Accept", "application/json"); + httpPost.setHeader("Content-Type", "application/json"); + RequestConfig defaultRequestConfig = RequestConfig.custom() + .setSocketTimeout(10000) + .setConnectTimeout(10000) + .setConnectionRequestTimeout(10000) + .build(); + httpPost.setConfig(defaultRequestConfig); + String charSet = "UTF-8"; + StringEntity entity = new StringEntity(params, charSet); + httpPost.setEntity(entity); + CloseableHttpResponse response = null; + HttpClientContext context = HttpClientContext.create(); + try { + + response = httpclient.execute(httpPost, context); + StatusLine status = response.getStatusLine(); + int state = status.getStatusCode(); + if (state == HttpStatus.SC_OK) { + HttpEntity responseEntity = response.getEntity(); + String jsonString = EntityUtils.toString(responseEntity); + return jsonString; + } else { + //do log + } + } finally { + if (response != null) { + try { + response.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + try { + httpclient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } +} \ No newline at end of file diff --git a/src/main/java/com/fxzy/warn/common/util/JWTUtil.java b/src/main/java/com/fxzy/warn/common/util/JWTUtil.java new file mode 100644 index 0000000..f6effe9 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/util/JWTUtil.java @@ -0,0 +1,189 @@ +package com.fxzy.warn.common.util; + + +//import com.lzrq.template.model.User; + +import com.baomidou.mybatisplus.core.toolkit.StringUtils; + +import com.nimbusds.jose.*; +import com.nimbusds.jose.crypto.MACSigner; +import com.nimbusds.jose.crypto.MACVerifier; +import net.minidev.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.text.ParseException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * JWT 加密 + * + * @author yuchen + * @date 2020/05/07 + */ +@Component +public class JWTUtil { + + private final Logger logger = LoggerFactory.getLogger(JWTUtil.class); + + + @Autowired + private RedisUtil redisUtil; + + private String publicKey; + + + /** + * 获取共有密匙 + */ + public String getPublicKey() { + // String publicKey = null; + if (publicKey != null) { + return publicKey; + } + synchronized (this) { + if (publicKey != null) { + return publicKey; + } + + try { + publicKey = redisUtil.getString("gas_wx_public_key"); + if (StringUtils.isBlank(publicKey)) { + // publicKey = UUID.randomUUID().toString().replace("-", ""); + publicKey = "2bccf9dc91d240b8ad7f303a7e3f3d63"; + redisUtil.setString("publicKey", publicKey, 0); + } + } catch (Exception e) { + logger.error("获取共有密匙异常,errMsg==={}", e.getMessage()); + } + return publicKey; + } + } + + +// public String creatToken(WxUserVO user, String publicKey) throws JOSEException { +// if (null == user || StringUtils.isBlank(publicKey)) { +// return null; +// } +// //3.先建立一个头部Header +// /** +// * JWSHeader参数:1.加密算法法则,2.类型,3.。。。。。。。 +// * 一般只需要传入加密算法法则就可以。 +// * 这里则采用HS256 +// * +// * JWSAlgorithm类里面有所有的加密算法法则,直接调用。 +// */ +// JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.HS256); +// +// Map payloadMap = createPayloadMap(user); +// +// //建立一个载荷Payload +// Payload payload = new Payload(new JSONObject(payloadMap)); +// +// //将头部和载荷结合在一起 +// JWSObject jwsObject = new JWSObject(jwsHeader, payload); +// +// //建立一个密匙 +// +// JWSSigner jwsSigner = new MACSigner(publicKey.getBytes()); +// +// //签名 +// jwsObject.sign(jwsSigner); +// +// //生成token +// return jwsObject.serialize(); +// } + + /** + * 根据token解析当前登陆者信息 + */ + /** + * 根据token解析当前登陆者信息 + */ +// public WxUserVO getUserByToken(String token) { +// +// if (StringUtils.isBlank(token)) { +// return null; +// } +// WxUserVO user = null; +// try { +// JWSObject jwsObject = JWSObject.parse(token); +// //获取到载荷 +// Payload payload = jwsObject.getPayload(); +// JSONObject jsonObject = payload.toJSONObject(); +// String result = jsonObject.toString(); +// user = com.alibaba.fastjson.JSONObject.parseObject(result, WxUserVO.class); +// if (StringUtils.isNotBlank(user.getId())) { +// String userId = user.getId(); +// user.setId(userId.substring(0, userId.length() - 14)); +// } +// } catch (ParseException e) { +// e.printStackTrace(); +// } +// return user; +// } + + + /** + * 验证token + */ + public boolean validateToken(String token) { + boolean success = false; + if (StringUtils.isNotBlank(token)) { + try { + JWSObject jwsObject = JWSObject.parse(token); + String publicKey = redisUtil.getString("publicKey"); + //建立一个解锁密匙 + JWSVerifier jwsVerifier = new MACVerifier(publicKey.getBytes()); + if (jwsObject.verify(jwsVerifier)) { + boolean exist = redisUtil.ifExist("token", token); + if (exist) { + success = true; + } + } + } catch (ParseException e1) { + logger.error("token解析失败,errMsg==={}", e1.getMessage()); + } catch (JOSEException e2) { + logger.error("密匙解析失败,errMsg==={}", e2.getMessage()); + } catch (NullPointerException e3) { + logger.error("token验证失败,errMsg==={}", e3.getMessage()); + } + } + return success; + } + +// public Map createPayloadMap(WxUserVO user) { +// Map payloadMap = new HashMap<>(16); +// if (StringUtils.isNotBlank(user.getId())) { +// payloadMap.put("id", user.getId() + TimeUtil.formatDateToTime(new Date())); +// } +// if (StringUtils.isNotBlank(user.getNodeCode())) { +// payloadMap.put("nodeCode", user.getNodeCode()); +// } +// if (StringUtils.isNotBlank(user.getUserName())) { +// payloadMap.put("username", user.getUserName()); +// } +// if (StringUtils.isNotBlank(user.getMobilePhone())) { +// payloadMap.put("mobilePhone", user.getMobilePhone()); +// } +// if (null!=user.getEnterpriseId()) { +// payloadMap.put("enterpriseId", user.getEnterpriseId()); +// } +// if (null!=user.getUserIdentity()) { +// payloadMap.put("userIdentity", user.getUserIdentity()); +// } +// if (StringUtils.isNotBlank(user.getOpenId())) { +// payloadMap.put("openId", user.getOpenId()); +// } +// return payloadMap; +// } + + + + +} diff --git a/src/main/java/com/fxzy/warn/common/util/LawResearchUtil.java b/src/main/java/com/fxzy/warn/common/util/LawResearchUtil.java new file mode 100644 index 0000000..7da4827 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/util/LawResearchUtil.java @@ -0,0 +1,949 @@ +package com.fxzy.warn.common.util; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.fxzy.warn.common.constants.LawResearchUrlConstants; +import org.springframework.http.*; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; + +/** + * @author zhangjing + * @date 2024/09/19 09:58 + * @description + */ +public class LawResearchUtil { + +// code 1000 请求成功 +// code 2001 客户端请求参数有误,服务器无法理解 +// code 2002 ticket 无效。客户端未能提供有效的认证信息 +// code 2003 authorize 无效。服务器拒绝执行此请求 +// code 3001 请求失败 + + + /** + * 司法模型 + * + * @param name + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String querySssxxg(String name, String creditCode) { + + //默认测试数据 + if (name == null) { + name = "四川无声信息技术有限公司"; + creditCode = "915101007234134581"; + } + + JSONArray array = new JSONArray(); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", name); + jsonObject.put("creditCode", creditCode); + jsonObject.put("authorize", 1); + array.add(jsonObject); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.QUERY_SSSXXG, + array, null, null + ); + } + + /** + * 工商模型 + * + * @param name + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String queryEntInfo(String name, String creditCode) { + //默认测试数据 + if (name == null) { + name = "四川无声信息技术有限公司"; + creditCode = "915101007234134581"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", name); + jsonObject.put("creditCode", creditCode); + jsonObject.put("authorize", 1); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.QUERY_ENT_INFO, + null, jsonObject, null + ); + } + /** + * 工商基础 + * + * @param name + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String entInfo(String name, String creditCode) { + //默认测试数据 + if (name == null) { + name = "四川无声信息技术有限公司"; + creditCode = "915101007234134581"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", name); + jsonObject.put("creditCode", creditCode); + jsonObject.put("authorize", 1); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.COMPANY_ENTINFO, + null, jsonObject, null + ); + } + + /** + * 制裁实体详情接口 + * + * @param name + * @param pageSize + * @param pageNum + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String sanctionName(String name, Integer pageSize, Integer pageNum) { + //默认测试数据 + if (name == null) { + name = "华为"; + pageSize = 20; + pageNum = 1; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", name); + jsonObject.put("pageSize", pageSize); + jsonObject.put("pageNum", pageNum); + jsonObject.put("authorize", 1); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.SANCTION_NAME, + null, jsonObject, null + ); + } + + /** + * 一般纳税人 + * + * @param name + * @param pageSize + * @param pageNum + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String generalTaxpayer(String name, Integer pageSize, Integer pageNum) { + //默认测试数据 + if (name == null) { + name = "小米科技有限责任公司"; + pageSize = 20; + pageNum = 1; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", name); + jsonObject.put("pageSize", pageSize); + jsonObject.put("pageNum", pageNum); + jsonObject.put("authorize", 1); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.GENERAL_TAXPAYER, + null, jsonObject, null + ); + } + /** + * 股权图谱接口 + * + * @param companyName + * @param fromDate 开始日期 yyyy/MM/dd + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String atlas(String companyName, String fromDate) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + fromDate = "2022/01/01"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("fromDate", fromDate); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.ATLAS, + null, jsonObject, null + ); + } + /** + * 关联人物图谱接口 + * + * @param companyName + * @param fromDate 开始日期 yyyy/MM/dd + * @param legalPersionName 法人或者高管 + * @param creditcode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String riskCompany(String companyName, String fromDate, String legalPersionName, String creditcode) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + fromDate = "2022/01/01"; + legalPersionName = "雷军"; + creditcode = "91110108551385082Q"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("fromDate", fromDate); + jsonObject.put("legalPersionName", legalPersionName); + jsonObject.put("creditcode", creditcode); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.RISK_COMPANY, + null, jsonObject, null + ); + } + + /** + * 债权债务趋势图接口 + * + * @param companyName + * @param minDate 开始日期(2019-07) + * @param maxDate 结束日期(2022-07) + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String caseTrendMap(String companyName, String minDate, String maxDate, String creditCode) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + minDate = "2019/01"; + maxDate = "2022/01"; + creditCode = "91110108551385082Q"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("minDate", minDate); + jsonObject.put("maxDate", maxDate); + jsonObject.put("creditCode", creditCode); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.CASE_TREND_MAP, + null, jsonObject, null + ); + } + + /** + * 企业司法画像-审理程序分布接口 + * + * @param companyName + * @param minDate 开始日期(2019-07) + * @param maxDate 结束日期(2022-07) + * @param type 3 刑事,4 民事,5 行政,6 执行 + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String getCaseAnalysisInfo(String companyName, String minDate, String maxDate, Integer type, String creditCode) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + minDate = "2019/01"; + maxDate = "2022/01"; + type = 4; + creditCode = "91110108551385082Q"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("minDate", minDate); + jsonObject.put("maxDate", maxDate); + jsonObject.put("type", type); + jsonObject.put("creditCode", creditCode); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.GET_CASE_TREND_MAP, + null, jsonObject, null + ); + } + + /** + * 企业司法画像-诉讼地位分布接口 + * + * @param companyName + * @param minDate + * @param maxDate + * @param type 3 刑事,4 民事,5 行政,6 执行 + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String getCaseSsdwInfo(String companyName, String minDate, String maxDate, Integer type, String creditCode) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + minDate = "2019/01"; + maxDate = "2022/01"; + type = 4; + creditCode = "91110108551385082Q"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("minDate", minDate); + jsonObject.put("maxDate", maxDate); + jsonObject.put("type", type); + jsonObject.put("creditCode", creditCode); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.GET_CASE_SSDW_INFO, + null, jsonObject, null + ); + } + + /** + * 企业司法画像-主诉/被诉诉讼结果接口 + * + * @param companyName + * @param minDate + * @param maxDate + * @param type 3 刑事,4 民事,5 行政,6 执行 + * @param litigationStatus 主诉/被诉 + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String getCaseSsjgInfo(String companyName, String minDate, String maxDate, Integer type, + String litigationStatus, String creditCode) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + minDate = "2019/01"; + maxDate = "2022/01"; + type = 4; + litigationStatus = "被诉"; + creditCode = "91110108551385082Q"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("minDate", minDate); + jsonObject.put("maxDate", maxDate); + jsonObject.put("type", type); + jsonObject.put("litigationStatus", litigationStatus); + jsonObject.put("creditCode", creditCode); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.GET_CASE_SSJG_INFO, + null, jsonObject, null + ); + } + + /** + * 企业司法画像-案件走势图接口 + * + * @param companyName + * @param minDate + * @param maxDate + * @param type 3 刑事,4 民事,5 行政,6 执行 + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String getCountAllCaseNumber(String companyName, String minDate, String maxDate, Integer type, + String creditCode) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + minDate = "2019/01"; + maxDate = "2022/01"; + type = 4; + creditCode = "91110108551385082Q"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("minDate", minDate); + jsonObject.put("maxDate", maxDate); + jsonObject.put("type", type); + jsonObject.put("creditCode", creditCode); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.COUNT_ALL_CASE_NUMBER, + null, jsonObject, null + ); + } + /** + * + * 企业司法画像-涉诉关系图接口 + * @param companyName + * @param minDate + * @param maxDate + * @param orderByField 排序字段:count 数量,amount 金额 + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + + public String litigationRelationship(String companyName, String minDate, String maxDate, + String orderByField, String creditCode) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + minDate = "2019/01"; + maxDate = "2022/01"; + orderByField = "count"; + creditCode = "91110108551385082Q"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("minDate", minDate); + jsonObject.put("maxDate", maxDate); + jsonObject.put("orderByField", orderByField); + jsonObject.put("creditCode", creditCode); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.LITIGATION_RELATIONSHIP, + null, jsonObject, null + ); + } + /** + * + * 企业司法画像-涉诉标的额接口 + * @param companyName + * @param minDate + * @param maxDate + * @param isCaseClosed 已结案、未结案(不传查全部) + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String countCaseLitigationAmountAll(String companyName, String minDate, String maxDate, + String isCaseClosed, String creditCode) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + minDate = "2019/01"; + maxDate = "2022/01"; + isCaseClosed = "已结案"; + creditCode = "91110108551385082Q"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("minDate", minDate); + jsonObject.put("maxDate", maxDate); + jsonObject.put("isCaseClosed", isCaseClosed); + jsonObject.put("creditCode", creditCode); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.COUNT_CASE_LITIGATION, + null, jsonObject, null + ); + } + /** + * + * 企业司法画像-地域分布图接口 + * @param companyName + * @param minDate + * @param maxDate + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String countCaseProvince(String companyName, String minDate, String maxDate, + String creditCode) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + minDate = "2019/01"; + maxDate = "2022/01"; + creditCode = "91110108551385082Q"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("minDate", minDate); + jsonObject.put("maxDate", maxDate); + jsonObject.put("creditCode", creditCode); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.COUNT_CASE_PROVINCE, + null, jsonObject, null + ); + } + /** + * + * 企业司法画像-案由分布图接口 + * @param companyName + * @param minDate + * @param maxDate + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String countSummary(String companyName, String minDate, String maxDate, + String creditCode) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + minDate = "2019/01"; + maxDate = "2022/01"; + creditCode = "91110108551385082Q"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("minDate", minDate); + jsonObject.put("maxDate", maxDate); + jsonObject.put("creditCode", creditCode); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.COUNT_SUMMARY, + null, jsonObject, null + ); + } + /** + * + * 投融资风险审查接口 + * @param companyName + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String riskReview(String companyName, + String creditCode) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + creditCode = "91110108551385082Q"; + } + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("creditCode", creditCode); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.RISK_REVIEW, + null, jsonObject, null + ); + } + /** + * + * 投融资风险详情接口 + * @param companyName + * @param pageIndex + * @param pageSize + * @param type 11 是否存在公司高管频繁变动 + * 12 是否存在股权结构异动 + * 13 当前是否存在股权抵押、质押等 + * 21 近五年与股东诉讼记录 + * 22 近五年与投资企业诉讼记录 + * 31 是否被列入制裁名单 + * 41 是否存在知产产权侵权风险 + * 42 是否不正当竞争风险 + * 51 股东/投资公司是否存在同业竞争 + * 61 是否存在重大风险 + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String pageInfo(String companyName,Integer pageIndex,Integer pageSize, + String type) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; +// creditCode = "91110108551385082Q"; + pageIndex = 1; + pageSize = 20; + type = "11"; + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("pageIndex", pageIndex); + jsonObject.put("pageSize", pageSize); + jsonObject.put("type", type); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.RISK_REVIEW_PAGE_INFO, + null, jsonObject, null + ); + } + /** + * + * 投融资风险详情接口 + * @param companyName + * @param creditCode + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String overview(String companyName, + String creditCode) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; + creditCode = "91110108551385082Q"; + + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("creditCode", creditCode); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.OVERVIEW, + null, jsonObject, null + ); + } + /** + * + * 合同履约风险列表接口 + * @param companyName + * @param pageIndex + * @param pageSize + * @param type 1002 是否被列入异常记录 + * 1003 是否被列入严重违法记录 + * 2001 被破产重组 + * 2002 是否有可执行财产 + * 2003 行政处罚 + * 2004 司法涉诉债务情况 + * 2005 股权出质 + * 2006 动产 + * 3001 否被列入为限制高消费 + * 3002 是否被列入为失信记录 + * 3003 否被列入为历史限制高消费 + * 3004 是否被列入为历史失信记录 + * 3005 近三年是否被存在行政处罚 + * 3006 近三年是否被存在税收处罚 + * 3007 近三年是否被存在环保处罚 + * 4001 大额违约记录 + * 4002 合同违约情况 + * 5001 近三年是否存在产品质量风险 + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String overviewPageInfo(String companyName,Integer pageIndex,Integer pageSize, + String type) { + //默认测试数据 + if (companyName == null) { + companyName = "小米科技有限责任公司"; +// creditCode = "91110108551385082Q"; + pageIndex = 1; + pageSize = 20; + type ="1002"; + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("type", type); + jsonObject.put("pageIndex", pageIndex); + jsonObject.put("pageSize", pageSize); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.OVERVIEW_PAGE_INFO, + null, jsonObject, null + ); + } + /** + * + * 监控名单添加接口 + * @param name + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String addpublic(String name) { + //默认测试数据 + if (name == null) { + name = "小米科技有限责任公司"; +// creditCode = "91110108551385082Q"; + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", name); + JSONArray array = new JSONArray(); + array.add(jsonObject); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.ADD_PUBLIC, + array, null, null + ); + } + /** + * + * 监控名单删除接口 + * @param name + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String delcompany(String name) { + //默认测试数据 + if (name == null) { + name = "小米科技有限责任公司"; +// creditCode = "91110108551385082Q"; + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", name); + JSONArray array = new JSONArray(); + array.add(jsonObject); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.DEL_COMPANY, + array, null, null + ); + } + /** + * + * 监控名单查询接口 + * @param pageIndex + * @param pageSize + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String monitorQuery(Integer pageIndex,Integer pageSize) { + //默认测试数据 + if (pageIndex == null) { + pageIndex = 1; + pageSize = 20; + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("pageIndex", pageIndex); + jsonObject.put("pageSize", pageSize); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.MONITOR_QUERY, + null, jsonObject, null + ); + } + /** + * + * 监控信息获取 + * @param queryDate + * @param pageIndex + * @param pageSize + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String queryMonitorCases(String queryDate,Integer pageIndex,Integer pageSize) { + //默认测试数据 + if (queryDate == null) { + queryDate="2022-07-06"; + pageIndex = 1; + pageSize = 20; + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("queryDate", queryDate); + jsonObject.put("pageIndex", pageIndex); + jsonObject.put("pageSize", pageSize); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.QUERY_MONITOR_CASES, + null, jsonObject, null + ); + } + /** + * + * 不良记录审查结果接口 + * @param name + * @param id 身份证号 + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String badrecord(String name,String id) { + //默认测试数据 + if (name == null) { + name="文敏钊"; + id = "511133197301240418"; + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", name); + jsonObject.put("id", id); + jsonObject.put("authorize", 1); + JSONArray arr = new JSONArray(); + arr.add(jsonObject); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.BADRECORD, + arr, jsonObject, null + ); + } + /** + * + * 类案诉讼实体接口 + * @param enterprise + * @param startPublishDate yyyy-MM-dd + * @param endPublishDate yyyy-MM-dd + * @param pageNum + * @param pageSize + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String listByEnterprise(String enterprise,String startPublishDate, + String endPublishDate,Integer pageNum,Integer pageSize) { + //默认测试数据 + if (enterprise == null) { + enterprise ="恒大地产集团有限公司"; + startPublishDate="2020-01-01"; + endPublishDate="2024-01-01"; + pageNum = 1; + pageSize = 20; + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("pageNum", pageNum); + jsonObject.put("pageSize", pageSize); + jsonObject.put("enterprise", enterprise); + jsonObject.put("startPublishDate", startPublishDate); + jsonObject.put("endPublishDate", endPublishDate); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.LIST_BY_ENTERPRISE, + null, jsonObject, null + ); + } + /** + * + * 类案详情查询接口 + * @param docId 文书唯一id + * @param casecause + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String showById(String docId,String casecause) { + //默认测试数据 + if (docId == null) { + docId ="c95f296f-353a-4741-ba94-aac0009f877e"; + casecause="盗窃罪"; + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("docId", docId); + + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.QUERY_WS_SHOW_BY_ID, + null, jsonObject, null + ); + } + /** + * + * 类案详情列表接口 + * @param casecause + * @param pageNum + * @param pageSize + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String detailsList(String casecause,Integer pageNum,Integer pageSize) { + //默认测试数据 + if (casecause == null) { + casecause="盗窃罪"; + pageNum = 1; + pageSize = 20; + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("casecause", casecause); + jsonObject.put("pageNum", pageNum); + jsonObject.put("pageSize", pageSize); + + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.QUERY_WS_DETAILS_LIST, + null, jsonObject, null + ); + } + /** + * + * 获取文书接口 + * @param id 案号或文书id + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String queryws(String id) { + //默认测试数据 + if (id == null) { + id="(2022)黑民申4571号"; + + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("id", id); + + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.QUERYWS, + null, jsonObject, null + ); + } + /** + * + * 专利查询列表接口 + * @param companyName + * @param pageNum + * @param pageSize + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String zlQuery(String companyName,Integer pageNum,Integer pageSize) { + //默认测试数据 + if (companyName == null) { + companyName="小米科技有限责任公司"; + pageNum = 1; + pageSize = 20; + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("companyName", companyName); + jsonObject.put("pageNum", pageNum); + jsonObject.put("pageSize", pageSize); + + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.ZL_QUERY, + null, jsonObject, null + ); + } + /** + * + * 专利详情查询接口 + * @param id 专利id + * @return java.lang.String + * @author zhangjing + * @create 2024/9/19 + **/ + public String zlDetails(String id) { + //默认测试数据 + if (id == null) { + id="ac9djeeb5ad2ci5ec68jcdb52df2id6cb4jefb57dadiacc00"; + + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("id", id); + return getData(LawResearchUrlConstants.BASE_URL + LawResearchUrlConstants.ZL_DETAILS, + null, jsonObject, null + ); + } + + + + private String getData(String apiUrl, JSONArray array, JSONObject jsonObject, String method) { + RestTemplate restTemplate = new RestTemplate(); + HttpComponentsClientHttpRequestFactory requestFactory + = new HttpComponentsClientHttpRequestFactory(); + requestFactory.setConnectionRequestTimeout(60000); + requestFactory.setConnectTimeout(60000); + requestFactory.setReadTimeout(60000); + restTemplate.setRequestFactory(requestFactory); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("ticket", LawResearchUrlConstants.TICKET); + headers.set("Authorization", LawResearchUrlConstants.TICKET); + String request = (array != null) ? array.toJSONString() : jsonObject.toJSONString(); + try { + //需要对入参进行 aes 加密 + String requestBody = AES.aesEncrypt(request, LawResearchUrlConstants.KEY); + System.out.println("requestBody=====" + requestBody); + //设置访问的 Entity + HttpEntity entity = new HttpEntity<>(requestBody, headers); + //执行 请求 + + ResponseEntity result = + restTemplate.exchange(apiUrl, method == null ? HttpMethod.POST : HttpMethod.GET, entity, + String.class); + // 指定文件路径 + String filePath = "output.txt"; + String resultData=null; + try (PrintWriter writer = new PrintWriter(new File(filePath))) { + //接收到返回结果需要进行 aes 解密 + resultData = AES.aesDecrypt(result.getBody(), LawResearchUrlConstants.KEY); + // 写入内容 + writer.println(resultData); + + // 自动关闭,因为使用了 try-with-resources 语句 + } catch (FileNotFoundException e) { + System.err.println("文件未找到: " + e.getMessage()); + } + return resultData; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/src/main/java/com/fxzy/warn/common/util/RedisUtil.java b/src/main/java/com/fxzy/warn/common/util/RedisUtil.java new file mode 100644 index 0000000..73bbdd9 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/util/RedisUtil.java @@ -0,0 +1,678 @@ +package com.fxzy.warn.common.util; + + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.exceptions.JedisException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + + +/** + * Redis工具类 + * + * @author yuyantian + * @date 2021/09/07 14:30 + */ +@Component +public class RedisUtil { + + private Logger logger = LoggerFactory.getLogger(RedisUtil.class); + + + private static final String LOCK_SUCCESS = "OK"; + private static final String SET_IF_NOT_EXIST = "NX"; + private static final String SET_WITH_EXPIRE_TIME = "PX"; + private static final Long RELEASE_SUCCESS = 1L; + + private JedisPool jedisPool; + + public RedisUtil(JedisPool jedisPool) { + this.jedisPool = jedisPool; + } + + public void setex(final String key, final int seconds, final String value) { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + jedis.setex(key, seconds, value); + } catch (JedisException e) { + logger.error("redis 赋初值,设过期出错", e); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + public void incr(String key) { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + jedis.incr(key); + } catch (JedisException e) { + logger.error("redis 赋累加出错", e); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + /** + * 存入key、JSON化后的字符串 + */ + public void set(String key, T value, int seconds) { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + jedis.set(key, JSON.toJSONString(value)); + if (seconds != 0) { + jedis.expire(key, seconds); + } + } catch (JedisException e) { + logger.error("redis 赋初值出错 key:{},value:{}", key, value, e); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + /** + * 存入字符串 + */ + public void setString(String key, String value, int seconds) { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + jedis.set(key, value); + if (seconds != 0) { + jedis.expire(key, seconds); + } + } catch (JedisException e) { + logger.error("redis 赋初值出错", e); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + /** + * 读取字符串 + */ + public String getString(String key) { + Jedis jedis = null; + String result = null; + try { + jedis = jedisPool.getResource(); + if (!jedis.exists(key)) { + logger.info("redis 当前key 不存在"); + return result; + } + result = jedis.get(key); + } catch (JedisException e) { + logger.error("redis 获取对象出错", e); + handleJedisException(e); + return result; + } finally { + if (jedis != null) { + jedis.close(); + } + } + return result; + } + + /** + * 存入key、JSON化后的字符串 + */ + public Long setnx(String key, T value, int seconds) { + Jedis jedis = null; + Long setnx = 0L; + try { + jedis = jedisPool.getResource(); + setnx = jedis.setnx(key, JSON.toJSONString(value)); + if (seconds != 0) { + jedis.expire(key, seconds); + } + return setnx; + } catch (JedisException e) { + logger.error("redis 赋初值出错", e); + handleJedisException(e); + return setnx; + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + + /** + * 释放分布式锁 + * + * @param lockKey 锁 + * @param requestId 请求标识 + * @return 是否释放成功 + */ + public boolean releaseDistributedLock(String lockKey, String requestId) { + Jedis jedis = null; + try { + Object result = null; + jedis = jedisPool.getResource(); + String currentValue = jedis.get(lockKey); + if (StringUtils.trimToEmpty(currentValue).equals(StringUtils.trimToEmpty(requestId))) { + result = jedis.del(lockKey); + } + +// String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; +// Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId)); + + return RELEASE_SUCCESS.equals(result); + + } catch (JedisException e) { + logger.error("redis 分布式解锁异常", e); + handleJedisException(e); + return false; + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + + /** + * 获取JSON 对象 + */ + public boolean exists(String key) { + Jedis jedis = null; + boolean flag = false; + try { + jedis = jedisPool.getResource(); + flag = jedis.exists(key); + } catch (JedisException e) { + logger.error("redis 获取对象出错", e); + handleJedisException(e); + flag = false; + } finally { + if (jedis != null) { + jedis.close(); + } + } + return flag; + } + + /** + * 获取JSON 对象 + */ + public Object get(String key, Class cla) { + Jedis jedis = null; + Object data = null; + try { + jedis = jedisPool.getResource(); + if (!jedis.exists(key)) { + logger.info("redis 当前key 不存在"); + return data; + } + String value = jedis.get(key); + data = JSON.parseObject(value, cla); + } catch (JedisException e) { + logger.error("redis 获取对象出错", e); + handleJedisException(e); + return data; + } finally { + if (jedis != null) { + jedis.close(); + } + } + return data; + } + + /** + * 获取JSON 对象数组 + */ + public Object getArray(String key, Class cla) { + Jedis jedis = null; + Object data = null; + try { + jedis = jedisPool.getResource(); + if (!jedis.exists(key)) { + logger.info("redis 当前key 不存在"); + return data; + } + String value = jedis.get(key); + data = JSON.parseArray(value, cla); + } catch (JedisException e) { + logger.error("redis 获取对象数组出错", e); + handleJedisException(e); + return data; + } finally { + if (jedis != null) { + jedis.close(); + } + } + return data; + } + + /** + * 获取JSON 对象. + */ + public T getObject(String key, Class cla) { + Jedis jedis = null; + T data = null; + try { + jedis = jedisPool.getResource(); + if (!jedis.exists(key)) { + logger.info("redis 当前key 不存在"); + return data; + } + String value = jedis.get(key); + data = JSON.parseObject(value, cla); + } catch (JedisException e) { + logger.error("redis 获取对象出错", e); + handleJedisException(e); + return data; + } finally { + if (jedis != null) { + jedis.close(); + } + } + return data; + } + + /** + * 获取JSON 对象. + */ + public T getTypeReferenceObject(String key, TypeReference cla) { + Jedis jedis = null; + T data = null; + try { + jedis = jedisPool.getResource(); + if (!jedis.exists(key)) { + logger.info("redis 当前key 不存在"); + return data; + } + String value = jedis.get(key); + data = JSON.parseObject(value, cla); + } catch (JedisException e) { + logger.error("redis 获取对象出错", e); + handleJedisException(e); + return data; + } finally { + if (jedis != null) { + jedis.close(); + } + } + return data; + } + + /** + * 获取JSON 对象 剩余生命时间 + */ + public Long ttl(String key) { + Jedis jedis = null; + Long value = -1L; + try { + jedis = jedisPool.getResource(); + if (!jedis.exists(key)) { + value = -1L; + } else { + value = jedis.ttl(key); + } + } catch (JedisException e) { + logger.error("redis 获取对象出错", e); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + return value; + } + + /** + * 删除key + */ + public void del(String key) { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + if (!jedis.exists(key)) { + logger.info("redis 当前key 不存在"); + } + jedis.del(key); + } catch (JedisException e) { + logger.error("令牌删除失败", e); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + + /** + * 设置过期 + */ + public void expire(String key, int seconds) { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + if (!jedis.exists(key)) { + logger.info("redis 当前key 不存在"); + } + jedis.expire(key, seconds); + } catch (JedisException e) { + logger.error("redis 设置过期失败", e); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + /** + * 队列设置 + * 命令用来向列表左边增加元素,返回表示增加元素后列表的长度 + */ + public void lpush(String key, T value) { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + jedis.lpush(key, JSON.toJSONString(value)); + } catch (JedisException e) { + logger.error("redis 设置队列失败", e); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + /** + * 队列设置 + * 命令用来向列表右边增加元素,返回表示增加元素后列表的长度 + */ + public void rpush(String key, T value) { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + jedis.rpush(key, JSON.toJSONString(value)); + } catch (JedisException e) { + logger.error("redis 设置队列失败", e); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + /** + * 队列设置 + * 1:将列表左边的元素从列表中移除,2:返回被移除元素值 + */ + public Object lpop(String key, Class cla) { + Jedis jedis = null; + Object data = null; + try { + jedis = jedisPool.getResource(); + if (!jedis.exists(key)) { + logger.info("redis 当前key 不存在"); + return data; + } + String value = jedis.lpop(key); + data = JSON.parseObject(value, cla); + } catch (JedisException e) { + logger.error("redis lpop 失败"); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + return data; + } + + /** + * 队列设置 + * 1:将列表右边的元素从列表中移除,2:返回被移除元素值 + */ + public Object rpop(String key, Class cla) { + Jedis jedis = null; + Object data = null; + try { + jedis = jedisPool.getResource(); + String value = jedis.rpop(key); + if (!jedis.exists(key)) { + logger.info("redis 当前key 不存在"); + return data; + } + data = JSON.parseObject(value, cla); + } catch (JedisException e) { + logger.error("redis rpop 失败"); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + return data; + } + + /** + * 队列设置 + * 1:将列表右边的元素从列表中移除,2:返回被移除元素值 + */ + public List lpops(String key, Class cla) { + Jedis jedis = null; + List data = new ArrayList(); + try { + jedis = jedisPool.getResource(); + while (jedis.exists(key)) { + String value = jedis.lpop(key); + T t = JSON.parseObject(value, cla); + data.add(t); + } + } catch (JedisException e) { + logger.error("redis rpop 失败"); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + return data; + } + + /** + * 队列设置 + * 1:将列表右边的元素从列表中移除,2:返回被移除元素值 + */ + public List rpops(String key, Class cla) { + Jedis jedis = null; + List data = new ArrayList(); + try { + jedis = jedisPool.getResource(); + while (jedis.exists(key)) { + String value = jedis.rpop(key); + T t = JSON.parseObject(value, cla); + data.add(t); + } + } catch (JedisException e) { + logger.error("redis rpop 失败"); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + return data; + } + + /** + * 通过key通配符获取所有的key + */ + public List getKeys(String pattern) { + Jedis jedis = null; + List data = new ArrayList<>(); + try { + jedis = jedisPool.getResource(); + Set set = jedis.keys(pattern); + for (String key : set) { + data.add(key); + } + } catch (JedisException e) { + logger.error("redis rpop 失败 keys:" + pattern, e); + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + return data; + + } + + + /** + * Handle jedisException, write log and return whether the connection is broken. + */ + protected boolean handleJedisException(JedisException jedisException) { + if (jedisException instanceof JedisConnectionException) { + logger.error("Redis connection lost.", jedisException); + } else if (jedisException instanceof JedisDataException) { + if ((jedisException.getMessage() != null) && ( + jedisException.getMessage().indexOf("READONLY") != -1)) { + logger.error("Redis connection " + " are read-only slave.", jedisException); + } else { + return false; + } + } else { + logger.error("Jedis exception happen.", jedisException); + } + return true; + } + + public void hmset(final String key, final Map hash) { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + jedis.hmset(key, hash); + } catch (JedisException e) { + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + public Map hgetAll(final String key) { + Jedis jedis = null; + Map map = null; + + try { + jedis = jedisPool.getResource(); + map = jedis.hgetAll(key); + } catch (JedisException e) { + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + + return map; + } + + public void hdel(final String key, final String... fields) { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + jedis.hdel(key, fields); + } catch (JedisException e) { + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + /** + * 向set中添加字符串 + */ + public void addSetString(String key, String value) { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + jedis.sadd(key, value); + } catch (JedisException e) { + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + + /** + * 删除set中的值 + */ + public void delSetString(String key, String value) { + Jedis jedis = null; + try { + jedis = jedisPool.getResource(); + jedis.srem(key, value); + } catch (JedisException e) { + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + } + + /** + * 判断set中元素是存在 + */ + public boolean ifExist(String key, String value) { + Jedis jedis = null; + boolean exist = false; + try { + jedis = jedisPool.getResource(); + exist = jedis.sismember(key, value); + } catch (JedisException e) { + handleJedisException(e); + } finally { + if (jedis != null) { + jedis.close(); + } + } + return exist; + } + + +} diff --git a/src/main/java/com/fxzy/warn/common/util/ServletUtils.java b/src/main/java/com/fxzy/warn/common/util/ServletUtils.java new file mode 100644 index 0000000..294436a --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/util/ServletUtils.java @@ -0,0 +1,34 @@ +package com.fxzy.warn.common.util; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; + +public class ServletUtils { + + /** + * 获取当前线程正在处理的请求对象的 客户端ip + */ + public static String getRemoteIp() { + RequestAttributes reqAttr = RequestContextHolder.getRequestAttributes(); + if (reqAttr == null) { + return null; + } + HttpServletRequest request = ((ServletRequestAttributes) reqAttr).getRequest(); + String forwardIp = request.getHeader("x-forwarded-for"); + + if (StringUtils.isNotBlank(forwardIp)) { + // 多个反向代理应用服务系统会用 "," 分隔,取第一个就是客户端的 ip + // 如: 171.214.183.158, 172.23.22.42, 172.23.22.43 + String[] proxies = forwardIp.split(","); + if (proxies.length > 0) { + return proxies[0].trim(); + } + } + return request.getRemoteAddr(); + } + +} diff --git a/src/main/java/com/fxzy/warn/common/util/TimeUtil.java b/src/main/java/com/fxzy/warn/common/util/TimeUtil.java new file mode 100644 index 0000000..4d192cd --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/util/TimeUtil.java @@ -0,0 +1,609 @@ +package com.fxzy.warn.common.util; + +import org.apache.commons.lang3.StringUtils; +import org.apache.http.util.TextUtils; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * 时间工具类 + * @author yuyantian + * @date 2020/05/07 + */ +public class TimeUtil { + + + /** + * 时间戳字符串转时间 + * + * @param timestamp 毫秒 + */ + public static Date formatTimestampToDate(String timestamp) { + Date date = null; + if (StringUtils.isNotBlank(timestamp)) { + Long time = Long.parseLong(timestamp); + date = new Date(time); + } + return date; + } + + /** + * 获取当天时间字符串 + */ + public static String getTodayTimeStr() { + String result = null; + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date date = new Date(); + result = sdf.format(date); + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** + * 获取明天时间字符串 + */ + public static String getTomorrowTimeStr() { + String result = null; + SimpleDateFormat sdf = null; + Calendar c = null; + try { + sdf = new SimpleDateFormat("yyyy-MM-dd"); + c = new GregorianCalendar(); + c.setTime(new Date()); + c.add(c.DATE, 1); + result = sdf.format(c.getTime()); + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** + * 获取当日时间字符串 yyyyMMdd + */ + public static String formatTimeyyyyMMdd() { + String result = null; + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + Date date = new Date(); + result = sdf.format(date); + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** + * 将时间字符串转换成时间戳字符串 + * + * @param timeStr yyyy-MM-dd HH:mm:ss + */ + public static String formatTimeToTimestamp(String timeStr) { + String timestamp = ""; + if (StringUtils.isNotBlank(timeStr)) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + Date d = sdf.parse(timeStr); + timestamp = d.getTime() + ""; + } catch (ParseException e) { + e.printStackTrace(); + } + } + return timestamp; + } + + /** + * 将时间字符串转换成日期时间 + * + * @param timeStr yyyy-MM-dd HH:mm:ss + */ + public static Date formatTimeToDate(String timeStr) { + Date date = null; + if (StringUtils.isNotBlank(timeStr)) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + date = sdf.parse(timeStr); + } catch (ParseException e) { + e.printStackTrace(); + } + } + return date; + } + + + /** + * 将时间字符串转换成日期时间 + * + * @param timeStr yyyy-MM + */ + public static Date formatyyyyMMTimeToDate(String timeStr) { + Date date = null; + if (StringUtils.isNotBlank(timeStr)) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); + try { + date = sdf.parse(timeStr); + } catch (ParseException e) { + e.printStackTrace(); + } + } + return date; + } + + /** + * 将时间字符串转换成日期时间 + * + * @param timeStr yyyy-MM-dd + */ + public static Date formatyyyyMMddTimeToDate(String timeStr) { + Date date = null; + if (StringUtils.isNotBlank(timeStr)) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + date = sdf.parse(timeStr); + } catch (ParseException e) { + e.printStackTrace(); + } + } + return date; + } + /** + * 将时间转换成字符串 + * + * @param time yyyy-MM-dd HH:mm:ss + */ + public static String formatTimeToDate(Date time) { + String timeStr = null; + if (null!=time) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + timeStr = sdf.format(time); + } catch (Exception e) { + e.printStackTrace(); + } + } + return timeStr; + } + + /** + * 将时间转换成字符串 + * + * @param time yyyyMMddHHmmss + */ + public static String formatTimeyyyyMMddHHmmss(Date time) { + String timeStr = null; + if (null!=time) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); + try { + timeStr = sdf.format(time); + } catch (Exception e) { + e.printStackTrace(); + } + } + return timeStr; + } + + /** + * 时间转字符串 + * + * @param date yyyy-MM-dd + */ + public static String formatTimeStr(Date date) { + String timeStr = null; + if(null !=date){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + timeStr = sdf.format(date); + } catch (Exception e) { + e.printStackTrace(); + } + } + + return timeStr; + } + + /** + * 时间转字符串 + * + * @param date yyyy-MM-dd + */ + public static String formatTimeStryyyyMMddHHmmssSSS(Date date) { + String timeStr = null; + if(null !=date){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); + try { + timeStr = sdf.format(date); + } catch (Exception e) { + e.printStackTrace(); + } + } + return timeStr; + } + + /** + * 时间转字符串 + * + * @param date yyyy-MM-dd + */ + public static String formatTimeStryyyyMMddHHmm(Date date) { + + String timeStr = null; + if(null!=date){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + try { + timeStr = sdf.format(date); + } catch (Exception e) { + e.printStackTrace(); + } + } + return timeStr; + } + + public static String formatTimeStryyyyMMddHHmmssSSSNum(Date date) { + String timeStr = null; + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + try { + timeStr = sdf.format(date); + } catch (Exception e) { + e.printStackTrace(); + } + return timeStr; + } + + /** + * 获取明天时间 + * + * @param date yyyy-MM-dd + */ + public static String formatTomorrow(Date date) { + String timeStr = null; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.DAY_OF_MONTH, +1);//时间加一天 + Date tomorrow = calendar.getTime(); + timeStr = sdf.format(tomorrow); + } catch (Exception e) { + e.printStackTrace(); + } + return timeStr; + } + + /** + * 获取月底时间 + * + * @param date yyyy-MM-dd + */ + public static String getNextMonthFirst(Date date) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.MONTH, 1); + calendar.set(Calendar.DATE, 0); + return df.format(calendar.getTime()); + } + + + /** + * 获取计算相差天数的时间 + * + * @param timeStr yyyy-MM-dd + */ + public static String formatEndTime(String timeStr,int value) { + if (StringUtils.isNotBlank(timeStr)) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + Date d = sdf.parse(timeStr); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(d); + calendar.add(Calendar.DAY_OF_MONTH, +value);//时间加一天 + return sdf.format(calendar.getTime()); + } catch (ParseException e) { + e.printStackTrace(); + } + } + return null; + } + + /** + * 时间字符串转时间 + * + * @param dateStr yyyy-MM-dd + */ + public static Date formatDate(String dateStr) { + Date date = null; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + date = sdf.parse(dateStr); + } catch (Exception e) { + e.printStackTrace(); + } + return date; + } + + /** + * 日期转换成时间字符串 + * yyyyMMddHHmmss + */ + public static String formatDateToTime(Date date) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); + String time = sdf.format(date); + return time; + } + + /** + * 获取当月第一天 + * + * @return yyyy-MM-dd + */ + public static String getMonthOfFirst() { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Calendar cale = Calendar.getInstance(); + cale.add(Calendar.MONTH, 0); + cale.set(Calendar.DAY_OF_MONTH, 1); + String monthFirst = sdf.format(cale.getTime()); + return monthFirst; + } + + /** + * 获取当年第一天 + * + * @return yyyy-MM-dd + */ + public static String getYearOfFirst() { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Calendar cale = Calendar.getInstance(); + cale.add(Calendar.YEAR, 0); + cale.set(Calendar.DAY_OF_YEAR, 1); + String yearFirst = sdf.format(cale.getTime()); + return yearFirst; + } + + + /** + * 时间字符串转日期 + * yyyy-MM-dd + */ + public static Date dateStrFormatDate(String dateStr) { + Date d = null; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + d = sdf.parse(dateStr); + } catch (ParseException e) { + e.printStackTrace(); + } + return d; + } + + /** + * yyyy年MM月dd日转换为时间 + * @param dateStr + * @return + */ + public static Date format1(String dateStr){ + Date d = null; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"); + try { + d = sdf.parse(dateStr); + } catch (ParseException e) { + e.printStackTrace(); + } + return d; + } + + /** + * 参数为时间类型,获取该时间为星期几 + * @param date + * @return + */ + public static String getWeek(Date date){ + String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"}; + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1; + if(week_index<0){ + week_index = 0; + } + return weeks[week_index]; + } + + /** + * 参数为字符串类型,获取该时间为星期几 yyyy年MM月dd日格式的字符串 + * @param dateStr + * @return + */ + public static String getWeek(String dateStr){ + Date date = formatDate(dateStr); + String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"}; + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1; + if(week_index<0){ + week_index = 0; + } + return weeks[week_index]; + } + + public static Date formatyyyyMMddHHmmTimeToDate(String timeStr) { + Date date = null; + if (StringUtils.isNotBlank(timeStr)) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + try { + date = sdf.parse(timeStr); + } catch (ParseException e) { + e.printStackTrace(); + } + } + return date; + } + + + /** + * 获取指定 + * @param year + * @param month + * @return + */ + public static String getLastDayOfMonth(int year,int month) + { + Calendar cal = Calendar.getInstance(); + //设置年份 + cal.set(Calendar.YEAR,year); + //设置月份 + cal.set(Calendar.MONTH, month); + //获取当月最小值 + int lastDay = cal.getMinimum(Calendar.DAY_OF_MONTH); + //设置日历中的月份,当月+1月-1天=当月最后一天 + cal.set(Calendar.DAY_OF_MONTH, lastDay-1); + //格式化日期 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String lastDayOfMonth = sdf.format(cal.getTime()); + return lastDayOfMonth; + } + + + + /** + * 获取年份+月份 + * + * @param amount 月份+amount + * @return + */ + public static Integer getMonth(int amount) { + String month = ""; + SimpleDateFormat sdf = new SimpleDateFormat("MM"); + Calendar calendar = Calendar.getInstance(); + //获取月份 + calendar.add(Calendar.MONTH, amount); + month = sdf.format(calendar.getTime()); + return Integer.parseInt(month); + + } + + /** + * 获取当年月份集合 + * + * @return + */ + public static List getNowYearMonthList(int amount) { + ArrayList result = new ArrayList(); + SimpleDateFormat sdf = new SimpleDateFormat("MM");//格式化为年月 + Calendar min = Calendar.getInstance(); + Calendar max = Calendar.getInstance(); + min.add(Calendar.MONTH, 0); + min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); + min.add(Calendar.MONTH, -amount); + max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2); + Calendar curr = min; + while (curr.before(max)) { + result.add(Integer.parseInt(sdf.format(curr.getTime()))); + curr.add(Calendar.MONTH, 1); + } + return result; + } + + /** + * 得到当前日期的年份 + * @return + */ + public static String nowYear() { + Date date = new Date(); + SimpleDateFormat sdf = new SimpleDateFormat("YYYY"); + String times = sdf.format(date); + return times; + } + public static String getYear(Date date) { + SimpleDateFormat sdf = new SimpleDateFormat("YYYY"); + String times = sdf.format(date); + return times; + } + + public static String getMonth(Date date) { + SimpleDateFormat sdf = new SimpleDateFormat("MM"); + String times = sdf.format(date); + return times; + } + + /** + * 获取近amount年份集合 + * + * @return + */ + public static List getYearList(int amount) { + List result = new ArrayList<>(); + String currYear = nowYear(); + if(!TextUtils.isEmpty(currYear)){ + int currYear_int = Integer.parseInt(currYear); + result.add(currYear_int); + for (int i = 0;i < amount-1 ;i++){ + currYear_int--; + result.add(currYear_int); + } + } + return result; + } + + public static List getYearList(int amount,int nowYear) { + List result = new ArrayList<>(); + String currYear = String.valueOf(nowYear); + if(!TextUtils.isEmpty(currYear)){ + int currYear_int = Integer.parseInt(currYear); + result.add(currYear_int); + for (int i = 0;i < amount-1 ;i++){ + currYear_int--; + result.add(currYear_int); + } + } + return result; + } + + public static void main(String[] args) { + String dateStr="2023/01/01"; + Date date = null; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); + try { + date = sdf.parse(dateStr); + System.out.println(date); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 将指定的天数添加到给定的日期上 + * + * @param date + * @param days 要增加的天数 + * @return 增加天数后的日期字符串 + * @throws ParseException 如果日期字符串格式不正确,则抛出异常 + */ + public static Date addDaysToDate(Date date, int days) { + + // 使用Calendar来操作日期 + try{ + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(Calendar.DAY_OF_MONTH, days); // 增加天数 + return calendar.getTime(); + }catch (Exception e){ + e.printStackTrace(); + } + return date; + } + + + + /** + * 获取系统时间 + * @param + * @return + */ + public static Date getSystemDate(){ + return new Date(); + } +} diff --git a/src/main/java/com/fxzy/warn/common/util/treeUtil/ForestNodeManager.java b/src/main/java/com/fxzy/warn/common/util/treeUtil/ForestNodeManager.java new file mode 100644 index 0000000..27abb9a --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/util/treeUtil/ForestNodeManager.java @@ -0,0 +1,65 @@ +package com.fxzy.warn.common.util.treeUtil; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * @author zhangjing + * @date 2024/04/25 17:14 + * @description + */ +public class ForestNodeManager> { + /** + * 使用 ImmutableMap 存储节点,其中键是节点的ID,值是节点本身。 + * 这个映射是不可变的,通过调用 Maps.uniqueIndex(nodes, INode::getId) 来创建,其中 INode::getId 是获取节点ID的方法。 + * + * parentIdMap: 使用 HashMap 存储尚未创建的父节点的ID。键是父节点的ID,值是一个占位对象(在这里是空字符串)。 + */ + private final ImmutableMap nodeMap; + private final Map parentIdMap = Maps.newHashMap(); + + /** + * 接受一个 List 类型的参数 nodes,并使用 Maps.uniqueIndex 方法将其转换为 ImmutableMap 存储在 nodeMap 中 + */ + public ForestNodeManager(List nodes) { + this.nodeMap = Maps.uniqueIndex(nodes, INode::getId); + } + + /** + * 接受一个 Long 类型的节点ID作为参数,然后尝试从 nodeMap 中获取对应ID的节点。 + * 如果存在该节点,则返回节点;否则返回 null。 + */ + public INode getTreeNodeAt(Integer id) { + return this.nodeMap.containsKey(id) ? (INode)this.nodeMap.get(id) : null; + } + + /** + * 接受一个 Long 类型的父节点ID作为参数,将其添加到 parentIdMap 中。 + * 这个方法用于标记尚未创建的父节点。 + */ + public void addParentId(Integer parentId) { + this.parentIdMap.put(parentId, ""); + } + + /** + * 创建一个空的 ArrayList 用于存储树的根节点。 + * 使用 forEach 遍历 nodeMap 中的每个节点。 + * 对于每个节点,如果其父节点ID为0(表示是根节点)或者父节点ID在 parentIdMap 中存在(即尚未创建的父节点),则将该节点添加到根节点列表中。 + * 最后返回根节点列表。 + */ + public List getRoot() { + List roots = new ArrayList(); + this.nodeMap.forEach((key, node) -> { + if (node.getParentId() == 0L || this.parentIdMap.containsKey(node.getId())) { + roots.add(node); + } + + }); + return roots; + } +} + diff --git a/src/main/java/com/fxzy/warn/common/util/treeUtil/ForestNodeMerger.java b/src/main/java/com/fxzy/warn/common/util/treeUtil/ForestNodeMerger.java new file mode 100644 index 0000000..c0e9a5b --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/util/treeUtil/ForestNodeMerger.java @@ -0,0 +1,37 @@ +package com.fxzy.warn.common.util.treeUtil; + +import java.util.List; + +/** + * @author zhangjing + * @date 2024/04/25 17:16 + * @description + */ +public class ForestNodeMerger { + public ForestNodeMerger() { + } + + /** + * 对于每个节点,通过 getParentId() 方法获取其父节点的ID。 + * 如果父节点ID不等于0(即有父节点),则尝试通过 forestNodeManager.getTreeNodeAt() 方法获取父节点。 + * 如果成功获取到父节点,则将当前节点添加到父节点的子节点列表中。否则,说明父节点尚未被创建,需要通过 forestNodeManager.addParentId() 方法添加到待创建父节点的列表中。 + * + * 最后,通过 forestNodeManager.getRoot() 方法获取合并后的树的根节点列表,并返回这个列表。 + */ + public static > List merge(List items) { + ForestNodeManager forestNodeManager = new ForestNodeManager(items); + items.forEach((forestNode) -> { + if (forestNode.getParentId() != 0) { + INode node = forestNodeManager.getTreeNodeAt(forestNode.getParentId()); + if (node != null) { + node.getChildren().add(forestNode); + } else { + forestNodeManager.addParentId(forestNode.getId()); + } + } + + }); + return forestNodeManager.getRoot(); + } + +} diff --git a/src/main/java/com/fxzy/warn/common/util/treeUtil/INode.java b/src/main/java/com/fxzy/warn/common/util/treeUtil/INode.java new file mode 100644 index 0000000..2859e75 --- /dev/null +++ b/src/main/java/com/fxzy/warn/common/util/treeUtil/INode.java @@ -0,0 +1,22 @@ +package com.fxzy.warn.common.util.treeUtil; + +import java.io.Serializable; +import java.util.List; + +/** + * @author zhangjing + * @date 2024/04/25 17:13 + * @description + */ +public interface INode extends Serializable { + Integer getId(); + + Integer getParentId(); + + List getChildren(); + + default Boolean getHasChildren() { + return false; + } +} + diff --git a/src/main/java/com/fxzy/warn/controller/TestController.java b/src/main/java/com/fxzy/warn/controller/TestController.java new file mode 100644 index 0000000..b71faa1 --- /dev/null +++ b/src/main/java/com/fxzy/warn/controller/TestController.java @@ -0,0 +1,148 @@ +package com.fxzy.warn.controller; + +import com.fxzy.warn.common.constants.ResponseMsgConstants; +import com.fxzy.warn.common.request.RequestParameter; +import com.fxzy.warn.common.response.ApiResponse; +import com.fxzy.warn.model.Test; +import com.fxzy.warn.service.TestService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.Objects; + +/** + * @author yuyantian + * @date 2023/04/26 + */ +@Api(tags = "Test Api") +@RestController +@RequestMapping("test/") +@Slf4j +public class TestController { + + /** + * TestService服务 + */ + @Autowired + private TestService testService; + + @RequestMapping(value = "queryPage", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) + @ApiOperation(value = "分页查询xxx内容") + public ApiResponse queryPage(@ApiParam() @RequestBody RequestParameter parameter) { + log.info("分页查询 ==== 参数{" + parameter.toString() + "}"); + ApiResponse apiResponse = new ApiResponse(); + if (!Objects.isNull(parameter) && !Objects.isNull(parameter.getParameter())) { + try { + // Page result = testService.queryPage(parameter); + apiResponse.setData(testService.list()); + apiResponse.setMessage(ResponseMsgConstants.OPERATE_SUCCESS); + } catch (Exception e) { + log.error("查询错误,errMsg==={}", e.getMessage()); + e.printStackTrace(); + apiResponse.recordError(ResponseMsgConstants.OPERATE_FAIL); + } + } else { + apiResponse.recordError(ResponseMsgConstants.OPERATE_FAIL); + } + return apiResponse; + } + + /** + * 插入Test属性不为空的数据方法 + * + * @param + * @return + */ + @ResponseBody + @ApiOperation(value = "新增") + @RequestMapping(value = "add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + public ApiResponse add(@ApiParam() @RequestBody Test entity) { + log.info("新增==== 参数{" + entity != null ? entity.toString() : "null" + "}"); + ApiResponse apiResponse = new ApiResponse(); + if (!Objects.isNull(entity)) { + try { + boolean result = testService.saveModel(entity); + if (result) { + apiResponse.setMessage(ResponseMsgConstants.OPERATE_SUCCESS); + } else { + apiResponse.recordError(ResponseMsgConstants.OPERATE_FAIL); + } + } catch (Exception e) { + log.error("新增错误,errMsg==={}", e.getMessage()); + e.printStackTrace(); + apiResponse.recordError(ResponseMsgConstants.OPERATE_FAIL); + } + } else { + apiResponse.recordError(ResponseMsgConstants.OPERATE_FAIL); + } + return apiResponse; + } + + /** + * 修改 + * + * @param + * @return + */ + @ResponseBody + @ApiOperation(value = "修改") + @RequestMapping(value = "edit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + public ApiResponse edit(@ApiParam() @RequestBody Test entity) { + log.info("修改==== 参数{" + entity != null ? entity.toString() : "null" + "}"); + ApiResponse apiResponse = new ApiResponse(); + if (!Objects.isNull(entity)) { + try { + boolean result = testService.updateModel(entity); + if (result) { + apiResponse.setMessage(ResponseMsgConstants.OPERATE_SUCCESS); + } else { + apiResponse.recordError(ResponseMsgConstants.OPERATE_FAIL); + } + } catch (Exception e) { + log.error("修改错误,errMsg==={}", e.getMessage()); + e.printStackTrace(); + apiResponse.recordError(ResponseMsgConstants.OPERATE_FAIL); + } + } else { + apiResponse.recordError(ResponseMsgConstants.OPERATE_FAIL); + } + return apiResponse; + } + + /** + * 通过id删除Test数据方法 + * + * @param + * @return + */ + @ResponseBody + @ApiOperation(value = "删除") + @RequestMapping(value = "remove", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + public ApiResponse remove(@ApiParam() @RequestBody Test entity) { + log.info("删除 ==== 参数{" + entity != null ? entity.toString() : "null" + "}"); + ApiResponse apiResponse = new ApiResponse(); + if (!Objects.isNull(entity)) { + try { + boolean result = testService.deleteModel(entity); + if (result) { + apiResponse.setMessage(ResponseMsgConstants.OPERATE_SUCCESS); + } else { + apiResponse.recordError(ResponseMsgConstants.OPERATE_FAIL); + } + } catch (Exception e) { + log.error("删除错误,errMsg==={}", e.getMessage()); + e.printStackTrace(); + apiResponse.recordError(ResponseMsgConstants.OPERATE_FAIL); + } + } else { + apiResponse.recordError(ResponseMsgConstants.OPERATE_FAIL); + } + return apiResponse; + } + +} diff --git a/src/main/java/com/fxzy/warn/mapper/TestMapper.java b/src/main/java/com/fxzy/warn/mapper/TestMapper.java new file mode 100644 index 0000000..0753edc --- /dev/null +++ b/src/main/java/com/fxzy/warn/mapper/TestMapper.java @@ -0,0 +1,15 @@ +package com.fxzy.warn.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.fxzy.warn.model.Test; +import org.apache.ibatis.annotations.Mapper; + +/** + * @author yuyantian + * @date 2023/10/16 18:19 + * @description + */ +@Mapper +public interface TestMapper extends BaseMapper { + +} diff --git a/src/main/java/com/fxzy/warn/model/Test.java b/src/main/java/com/fxzy/warn/model/Test.java new file mode 100644 index 0000000..82f1628 --- /dev/null +++ b/src/main/java/com/fxzy/warn/model/Test.java @@ -0,0 +1,36 @@ +package com.fxzy.warn.model; + +import com.baomidou.mybatisplus.annotation.*; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + +/** + * @author yuyantian + * @date 2023/10/16 18:09 + * @description + */ + +@ApiModel("") +@Data +@EqualsAndHashCode(callSuper = true) +@Accessors(chain = true) +@TableName("") +public class Test extends Model { + /** + * id + */ + @ApiModelProperty("id") + @TableId(type = IdType.ASSIGN_UUID) + private String id; + /** + * 所属项目 + */ + @ApiModelProperty("name") + private String name; + + +} diff --git a/src/main/java/com/fxzy/warn/service/TestService.java b/src/main/java/com/fxzy/warn/service/TestService.java new file mode 100644 index 0000000..35bd5be --- /dev/null +++ b/src/main/java/com/fxzy/warn/service/TestService.java @@ -0,0 +1,45 @@ +package com.fxzy.warn.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.IService; +import com.fxzy.warn.common.request.RequestParameter; +import com.fxzy.warn.model.Test; + +/** + * @author yuyantian + * @date 2023/10/16 18:17 + * @description + */ +public interface TestService extends IService { + + /** + * 保存 + * @param entity + * @return + */ + boolean saveModel(Test entity); + + /** + * 修改 + * @param entity + * @return + */ + boolean updateModel(Test entity); + + /** + * 删除 + * @param entity + * @return + */ + boolean deleteModel(Test entity); + + /** + * 分页查询 + * @param parameter + * @return + */ + Page queryPage(RequestParameter parameter); + + + +} diff --git a/src/main/java/com/fxzy/warn/service/impl/TestServiceImpl.java b/src/main/java/com/fxzy/warn/service/impl/TestServiceImpl.java new file mode 100644 index 0000000..402b284 --- /dev/null +++ b/src/main/java/com/fxzy/warn/service/impl/TestServiceImpl.java @@ -0,0 +1,50 @@ +package com.fxzy.warn.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.fxzy.warn.common.request.RequestParameter; +import com.fxzy.warn.mapper.TestMapper; +import com.fxzy.warn.model.Test; +import com.fxzy.warn.service.TestService; +import org.springframework.stereotype.Service; + +/** + * @author yuyantian + * @date 2023/10/16 18:17 + * @description + */ +@Service +public class TestServiceImpl extends ServiceImpl implements + TestService { + + @Override + public boolean saveModel(Test entity) { + boolean result = this.save(entity); + return result; + } + + @Override + public boolean updateModel(Test entity) { + boolean result = this.updateById(entity); + return result; + } + + @Override + public boolean deleteModel(Test entity) { + boolean result = this.removeById(entity); + + return result; + } + + @Override + public Page queryPage(RequestParameter parameter) { + Test entity = parameter.getParameter().toJavaObject(Test.class); + Page page = new Page(parameter.getCurrent(), parameter.getSize()); + page.setSearchCount(true); + page.setOptimizeCountSql(true); + QueryWrapper eWrapper = new QueryWrapper(entity); + Page result = this.page(page, eWrapper); + return result; + } +} diff --git a/src/main/resources/bootstrap-dev.yml b/src/main/resources/bootstrap-dev.yml new file mode 100644 index 0000000..708ffb1 --- /dev/null +++ b/src/main/resources/bootstrap-dev.yml @@ -0,0 +1,60 @@ +server: + port: 12104 + +spring: + datasource: + driver-class-name: com.kingbase8.Driver + url: jdbc:kingbase8://47.109.88.209:54321/gas?currentSchema=gas_service_db + username: root + password: zjtc321! + druid: + #配置初始化连接数大小 + initial-size: 50 + # 最大连接数 + maxActive: 150 + #最小连接数 + minIdle: 50 + #获取连接等待超时时间 + maxWait: 5000 + + #Redis + redis: + host: 47.109.88.209 + port: 63799 + password: zjtc321! + pool: + max-total: 500 + max-idle: 100 + max-wait: 10 + min-idle: 1 + timeout: 6000 + + +mybatis-plus: + configuration: + # 驼峰转换 从数据库列名到Java属性驼峰命名的类似映射 + map-underscore-to-camel-case: true + # 是否开启缓存 + cache-enable: false + # 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段 + #call-setters-on-nulls: true + # 打印sql + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + call-setters-on-nulls: true + +minio: + host: http://47.109.88.209:9000 + url: ${minio.host}/${minio.bucket}/ + access-key: zjtc + secret-key: zjtc321! + bucket: cert + +file: + #附件上传盘符,liunx服务器需要切换 + fileUploadRootPath: D:/ + fileUploadPath: /upload/ + + + + + diff --git a/src/main/resources/bootstrap-prod.yml b/src/main/resources/bootstrap-prod.yml new file mode 100644 index 0000000..e6df39f --- /dev/null +++ b/src/main/resources/bootstrap-prod.yml @@ -0,0 +1,48 @@ +server: + port: 12101 + +spring: + datasource: + driver-class-name: com.kingbase8.Driver + url: jdbc:kingbase8://47.109.88.209:54321/gas?currentSchema=gas_service_db + username: root + password: zjtc321! + druid: + #配置初始化连接数大小 + initial-size: 50 + # 最大连接数 + maxActive: 150 + #最小连接数 + minIdle: 50 + #获取连接等待超时时间 + maxWait: 5000 + + #Redis + redis: + host: 47.109.88.209 + port: 63799 + password: zjtc321! + pool: + max-total: 500 + max-idle: 100 + max-wait: 10 + min-idle: 1 + timeout: 6000 + + +mybatis-plus: + configuration: + # 驼峰转换 从数据库列名到Java属性驼峰命名的类似映射 + map-underscore-to-camel-case: true + # 是否开启缓存 + cache-enable: false + # 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段 + #call-setters-on-nulls: true + # 打印sql + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + call-setters-on-nulls: true + + + + + diff --git a/src/main/resources/bootstrap.yml b/src/main/resources/bootstrap.yml new file mode 100644 index 0000000..b4dd0c9 --- /dev/null +++ b/src/main/resources/bootstrap.yml @@ -0,0 +1,53 @@ +#tomcat配置 +server: + servlet-path: /fxzy_warn + servlet: + session: + + timeout: 12101 + tomcat: + uri-encoding: UTF-8 + #最小线程数 + min-spare-threads: 500 + #最大线程数 + max-threads: 2500 + #最大链接数 + max-connections: 6500 + #最大等待队列长度 + accept-count: 1000 + #请求头最大长度kb + max-http-header-size: 1048576 + +#系统配置 +spring: + http: + # 配置文件上传大小限制 + multipart: + maxFileSize: 200MB + maxRequestSize: 200MB + profiles: + active: dev + application: + name: fxzy_warn + + +#MyBatis-Plus 配置 +mybatis-plus: + global-config: + db-config: + logic-delete-field: false + logic-delete-value: 1 + logic-not-delete-value: 0 + configuration: + call-setters-on-nulls: true + +# swagger开关 +swagger: + enable: true + +# 短信开关 +sms: + enable: false + + + diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..14a8349 --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,236 @@ + + + + + + + + + + + + + + + + + + + + + + + + + ${CONSOLE_LOG_PATTERN} + + + + + + + + false + + log/${APP_NAME}-${APP_PROFILE}-info.log + + + + log/${APP_NAME}-info-%d{yyyy-MM-dd}.%i.log.zip + + 30 + 100MB + 10GB + + true + + + ${FILE_LOG_PATTERN} + utf8 + + + + INFO + ACCEPT + DENY + + + + + + + + false + + log/${APP_NAME}-${APP_PROFILE}-warn.log + + + + log/${APP_NAME}-warn-%d{yyyy-MM-dd}.%i.log.zip + + 30 + 100MB + 10GB + + true + + + ${FILE_LOG_PATTERN} + utf8 + + + + WARN + ACCEPT + DENY + + + + + + + + false + + log/${APP_NAME}-${APP_PROFILE}-error.log + + + + log/${APP_NAME}-error-%d{yyyy-MM-dd}.%i.log.zip + + 30 + 100MB + 10GB + + true + + + ${FILE_LOG_PATTERN} + utf8 + + + + ERROR + ACCEPT + DENY + + + + + + + + false + + log/${APP_NAME}-${APP_PROFILE}-debug.log + + + + log/${APP_NAME}-debug-%d{yyyy-MM-dd}.%i.log.zip + + 30 + 100MB + 10GB + + true + + + ${FILE_LOG_PATTERN} + utf8 + + + + DEBUG + ACCEPT + DENY + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/mapper/TestMapper.xml b/src/main/resources/mapper/TestMapper.xml new file mode 100644 index 0000000..db69e64 --- /dev/null +++ b/src/main/resources/mapper/TestMapper.xml @@ -0,0 +1,8 @@ + + + + + + + \ No newline at end of file diff --git a/src/main/resources/ueditor.json b/src/main/resources/ueditor.json new file mode 100644 index 0000000..06a07eb --- /dev/null +++ b/src/main/resources/ueditor.json @@ -0,0 +1,52 @@ +{ + "imageActionName": "uploadimage", + "imageFieldName": "upfile", + "imageMaxSize": 2048000, + "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".PNG", ".JPG", ".JPEG", ".GIF", ".BMP", ".WEBP"], + "imageCompressEnable": true, + "imageCompressBorder": 1600, + "imageInsertAlign": "none", + "imageUrlPrefix": "$urlPrefix", + "imagePathFormat": "project/ueditor/storage/image/{yyyy}{mm}{dd}/{time}", + "scrawlActionName": "uploadscrawl", + "scrawlFieldName": "upfile", + "scrawlPathFormat": "project/ueditor/storage/image/{yyyy}{mm}{dd}/{time}", + "scrawlMaxSize": 16777216, + "scrawlUrlPrefix": "$urlPrefix", + "scrawlInsertAlign": "none", + "snapscreenActionName": "uploadimage", + "snapscreenPathFormat": "project/ueditor/storage/image/{yyyy}{mm}{dd}/{time}", + "snapscreenUrlPrefix": "$urlPrefix", + "snapscreenInsertAlign": "none", + "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"], + "catcherActionName": "catchimage", + "catcherFieldName": "source", + "catcherPathFormat": "project/ueditor/storage/image/{yyyy}{mm}{dd}/{time}", + "catcherUrlPrefix": "$urlPrefix", + "catcherMaxSize": 16777216, + "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".PNG", ".JPG", ".JPEG", ".GIF", ".BMP"], + "videoActionName": "uploadvideo", + "videoFieldName": "upfile", + "videoPathFormat": "project/ueditor/storage/video/{yyyy}{mm}{dd}/{time}", + "videoUrlPrefix": "$urlPrefix", + "videoMaxSize": 16777216, + "videoAllowFiles": [".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", ".FLV", ".SWF", ".MKV", ".AVI", ".RM", ".RMVB", ".MPEG", ".MPG", ".OGG", ".OGV", ".MOV", ".WMV", ".MP4", ".WEBM", ".MP3", ".WAV", ".MID"], + "fileActionName": "uploadfile", + "fileFieldName": "upfile", + "filePathFormat": "project/ueditor/storage/file/{yyyy}{mm}{dd}/{time}", + "fileUrlPrefix": "$urlPrefix", + "fileMaxSize": 16777216, + "fileAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml", ".PNG", ".JPG", ".JPEG", ".GIF", ".BMP", ".FLV", ".SWF", ".MKV", ".AVI", ".RM", ".RMVB", ".MPEG", ".MPG", ".OGG", ".OGV", ".MOV", ".WMV", ".MP4", ".WEBM", ".MP3", ".WAV", ".MID", ".RAR", ".ZIP", ".TAR", ".GZ", ".7Z", ".BZ2", ".CAB", ".ISO", ".DOC", ".DOCX", ".XLS", ".XLSX", ".PPT", ".PPTX", ".PDF", ".TXT", ".MD", ".XML"], + "imageManagerActionName": "listimage", + "imageManagerListPath": "project/ueditor/storage/image/", + "imageManagerListSize": 20, + "imageManagerUrlPrefix": "$urlPrefix", + "imageManagerInsertAlign": "none", + "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".PNG", ".JPG", ".JPEG", ".GIF", ".BMP"], + "fileManagerActionName": "listfile", + "fileManagerListPath": "project/ueditor/storage/file/", + "fileManagerUrlPrefix": "$urlPrefix", + "fileManagerListSize": 20, + "fileManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid", ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml", ".PNG", ".JPG", ".JPEG", ".GIF", ".BMP", ".FLV", ".SWF", ".MKV", ".AVI", ".RM", ".RMVB", ".MPEG", ".MPG", ".OGG", ".OGV", ".MOV", ".WMV", ".MP4", ".WEBM", ".MP3", ".WAV", ".MID", ".RAR", ".ZIP", ".TAR", ".GZ", ".7Z", ".BZ2", ".CAB", ".ISO", ".DOC", ".DOCX", ".XLS", ".XLSX", ".PPT", ".PPTX", ".PDF", ".TXT", ".MD", ".XML"], + "serverUrl": "$serverUrl" +} \ No newline at end of file