一体化平台初始化仓库

This commit is contained in:
xlj
2026-02-09 13:04:45 +08:00
parent dd6040b580
commit daa67be814
48 changed files with 3747 additions and 0 deletions

108
assembly/assembly.xml Normal file
View File

@ -0,0 +1,108 @@
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<!--
必须写,不然打包时会有 assembly ID must be present and non-empty 错误
这个名字最终会追加到打包的名字的末尾,如项目的名字为 speed-api-0.0.1-SNAPSHOT,
则最终生成的包名为 speed-api-0.0.1-SNAPSHOT-bin.zip
-->
<id>bin</id>
<!-- 打包后的文件格式,能够是zip,tar,tar.gz,tar.bz2,jar,war,dir -->
<formats>
<format>zip</format>
</formats>
<!-- 压缩包下是否生成和项目名相同的根目录 -->
<includeBaseDirectory>false</includeBaseDirectory>
<!--<dependencySets>
<dependencySet>
&lt;!&ndash; 不使用项目的artifact第三方jar不要解压打包进zip文件的lib目录 &ndash;&gt;
<useProjectArtifact>true</useProjectArtifact>
<outputDirectory>lib</outputDirectory>
<unpack>false</unpack>
</dependencySet>
</dependencySets>-->
<!--依赖打包-->
<dependencySets>
<dependencySet>
<unpack>false</unpack>
<useProjectArtifact>true</useProjectArtifact>
<outputDirectory>lib</outputDirectory>
<scope>provided</scope>
</dependencySet>
<dependencySet>
<unpack>false</unpack>
<useProjectArtifact>true</useProjectArtifact>
<outputDirectory>lib</outputDirectory>
<scope>system</scope>
</dependencySet>
<dependencySet>
<unpack>false</unpack>
<useProjectArtifact>true</useProjectArtifact>
<outputDirectory>lib</outputDirectory>
<scope>runtime</scope>
</dependencySet>
</dependencySets>
<moduleSets>
<moduleSet>
<useAllReactorProjects>true</useAllReactorProjects>
<includes>
<include>integration-platform-access:cdaxxt-bootstrap</include>
<include>integration-platform-access:cdaxxt-business</include>
<include>integration-platform-access:cdaxxt-common</include>
<include>integration-platform-access:cdaxxt-core</include>
</includes>
<!--<binaries>
<outputDirectory>lib</outputDirectory>
<unpack>false</unpack>
</binaries>-->
</moduleSet>
</moduleSets>
<fileSets>
<!-- 把项目相关的说明文件打包进zip文件的根目录 -->
<fileSet>
<directory>${project.basedir}</directory>
<outputDirectory></outputDirectory>
<includes>
<include>README*</include>
<include>LICENSE*</include>
<include>NOTICE*</include>
</includes>
</fileSet>
<!-- 把项目的配置文件打包进zip文件的config目录 -->
<fileSet>
<directory>../cdaxxt-bootstrap/src/main/resources</directory>
<outputDirectory>config</outputDirectory>
<includes>
<include>*.yml</include>
</includes>
</fileSet>
<!-- 把项目的脚本文件打包进zip文件的bin目录 -->
<fileSet>
<directory>../cdaxxt-bootstrap/src/main/resources/bin</directory>
<outputDirectory></outputDirectory>
<!-- 文件文件权限为777 -->
<fileMode>777</fileMode>
<!-- 目录权限为777 -->
<directoryMode>777</directoryMode>
</fileSet>
<!-- 把项目本身编译出来的jar文件打包进zip文件的根目录 -->
<fileSet>
<directory>../cdaxxt-bootstrap/target</directory>
<outputDirectory></outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
</fileSets>
</assembly>

63
assembly/pom.xml Normal file
View File

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>integration-platform-access</artifactId>
<groupId>com.tobacco.mp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>assembly</artifactId>
<dependencies>
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>cdaxxt-bootstrap</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>cdaxxt-business</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>cdaxxt-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>cdaxxt-core</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4.1</version>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>assembly-package</finalName>
<descriptors>
<descriptor>assembly.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

72
cdaxxt-bootstrap/pom.xml Normal file
View File

@ -0,0 +1,72 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>integration-platform-access</artifactId>
<groupId>com.tobacco.mp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cdaxxt-bootstrap</artifactId>
<dependencies>
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>cdaxxt-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>cdaxxt-business</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>cdaxxt-core</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
<include>static/**</include>
</includes>
</resource>
</resources>
<plugins>
<!-- 指定启动类将依赖打成外部jar包 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<!-- 生成的jar中不要包含pom.xml和pom.properties这两个文件 -->
<addMavenDescriptor>false</addMavenDescriptor>
<manifest>
<!-- 是否要把第三方jar放到manifest的classpath中 -->
<addClasspath>true</addClasspath>
<!-- 外部依赖jar包的最终位置 -->
<classpathPrefix>lib/</classpathPrefix>
<!-- 项目启动类 -->
<mainClass>com.tobacco.mp.BasisApplication</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,19 @@
package com.tobacco.mp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@EnableFeignClients(basePackages = {"com.tobacco.mp.uc.client.api","com.tobacco.mp.auth.businessdomain.auth.client.api","com.tobacco.mp.mcext.client.api","com.tobacco.mp.ttc.client.api"})
@EnableAsync
@SpringBootApplication(scanBasePackages = {"com.tobacco.mp"})
public class BasisApplication {
public static void main(String[] args) {
SpringApplication.run(BasisApplication.class, args);
}
}

View File

@ -0,0 +1,24 @@
package com.tobacco.mp.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* 阿里云网关包扫描配置
*/
@Slf4j
@Configuration
@ConditionalOnExpression("'ali'.equals('${bizworks-api-gateway.type}') and 'true'.equals('${bizworks-api-gateway.enable}') ")
@ComponentScan("com.bizworks.ubcp.apiclient.feign")
public class BizworksApiGatewayConfiguration {
@Bean
public String init(){
log.info("开启阿里网关模式");
return null;
}
}

View File

@ -0,0 +1,52 @@
package com.tobacco.mp.config;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 跨域处理机制
*/
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
String origin = request.getHeader("Origin");
String allowHeaders = request.getHeader("Access-Control-Request-Headers");
if (!StringUtils.isEmpty(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
} else {
response.setHeader("Access-Control-Allow-Origin", "*");
}
if (!StringUtils.isEmpty(allowHeaders)) {
response.setHeader("Access-Control-Allow-Headers", allowHeaders);
} else {
response.setHeader("Access-Control-Allow-Headers", "*");
}
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}

View File

@ -0,0 +1,107 @@
package com.tobacco.mp.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* redis配置
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* retemplate相关配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值默认使用JDK的序列化方式
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域field,get和set,以及修饰符范围ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型类必须是非final修饰的final修饰的类比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
/**
* 对hash类型的数据操作
* @param redisTemplate
* @return
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 对redis字符串类型数据操作
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 对链表类型的数据操作
* @param redisTemplate
* @return
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 对无序集合类型的数据操作
* @param redisTemplate
* @return
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 对有序集合类型的数据操作
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}

View File

@ -0,0 +1,19 @@
package com.tobacco.mp.config;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 请求拦截器处理
*/
public class RequestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 请求拦截处理
return true;
}
}

View File

@ -0,0 +1,20 @@
package com.tobacco.mp.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class ServerRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// 服务器成功启动加载其他
}
}

View File

@ -0,0 +1,43 @@
package com.tobacco.mp.config;
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.WebMvcConfigurer;
/**
* @Author XiongLiJian
* @Date 2021/12/28 15:36
* @Description 资源管理配置
* @Version 1.0
**/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 声明需要放行的swagger资源路径
*/
private String[] newPassPath = new String[]{"/login", "/swagger-ui.html/**", "/v2/**","/files/**", "/webjars/**", "/swagger-resources/**",
"/**.js", "/static/**", "/images/**", "/index.html", "/css/**", "/js/**", "/file/**"};
/**
* 添加资源站点
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
}
/**
* 注册拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册拦截器
registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/**").excludePathPatterns(newPassPath);
}
}

View File

@ -0,0 +1,106 @@
server:
host: 0.0.0.0
port: 8049
compression:
enabled: true
servlet:
context-path: /mosty-platform
spring:
aop:
auto: true
application:
name: integration-platform-access
jackson:
date-format: yyyy-MM-dd HH:mm:ss
resources:
static-locations: classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/, classpath:/templates/
servlet:
multipart:
max-file-size: 20MB
max-request-size: 20MB
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://47.108.232.77:4407/mosty_jcgl_gs?autoReconnect=true&failOverReadOnly=false&useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true&rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai
username: root
password: Mosty@888
druid: # 以下参数针对每个库可以重新设置druid参数
# 使用druid数据源
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
redis:
host: 47.108.232.77
port: 6379
password: sczy@2022
timeout: 10000
max-active: 100
min-idle: 0
max-idle: 20
max-wait: 30000
sxExpire: 1800
database: 12
thymeleaf:
prefix: classpath:/templates/
mode: HTML5
suffix: .html
encoding: UTF-8
cache: false
servlet:
content-type: text/html
enabled: true
# mybatis
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.nologging.NoLoggingImpl
map-underscore-to-camel-case: true
cache-enabled: false
global-config:
db-config:
logic-delete-field: actived
logic-delete-value: 0
logic-not-delete-value: 1
table-underline: true
update-strategy: ignored
banner: false
logging:
file:
name: ${user.dir}/logs/${spring.application.name}/${spring.application.name}.log
level:
org.springframework.cloud.openfeign: DEBUG
feign: DEBUG
#feign:
# client:
# config:
# default:
# contract: org.springframework.cloud.openfeign.support.SpringMvcContract
bizworks:
clientId: 6f938da0e22911f0bc71bc16950a55fb
bizworks-api-gateway:
enable: true
type: ali
disSignService:
signature:
- host: api.gansu-ywzt.zgs.yun
appKey: 1762305806807768
appSecret: 5e1385488c054e9980bf0bf8e68c10a5
bizId:
service: tobacco-mp-uc-client

View File

@ -0,0 +1,212 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="application/msword; charset=utf-8"/>
<title>toWord</title>
<style type="text/css">
.bg {
font-size: 14.5px;
font-weight: bold;
color: #000;
background-color: #559e68;
}
table {
border-width: 1px;
border-style: solid;
border-color: black;
table-layout: fixed;
}
tr {
height: 32px;
font-size: 12px;
}
td {
padding-left: 10px;
border-width: 1px;
border-style: solid;
border-color: black;
height: 32px;
overflow: hidden;
word-break: break-all;
word-wrap: break-word;
font-size: 14.5px;
}
.bg td {
font-size: 14.5px;
}
tr td {
font-size: 14.5px;
}
.specialHeight {
height: 40px;
}
.first_title {
height: 60px;
line-height: 60px;
margin: 0;
font-weight: bold;
font-size: 21px;
}
.second_title {
height: 40px;
line-height: 40px;
margin: 0;
font-size: 18.5px;
}
.doc_title {
font-size: 42.5px;
text-align: center;
}
.download_btn {
float: right;
}
body {
font-family: Normal;
}
</style>
</head>
<body>
<div style="width:1000px; margin: 0 auto">
<div>
<p class="doc_title" th:text="${info.title +''+ info.version +''}"></p>
<a class="download_btn" th:if="${download == 1}" th:href="${'/downloadWord?url='+ url}">下载文档</a>
<br>
</div>
<div th:each="tableMap:${tableMap}" style="margin-bottom:20px;">
<!--这个是类的说明-->
<h4 class="first_title" th:text="${tableMap.key}"></h4>
<div th:each="table,tableStat:${tableMap.value}">
<!--这个是每个请求的说明,方便生成文档后进行整理-->
<h5 class="second_title" th:text="${tableStat.count} + '' + ${table.tag}"></h5>
<table border="1" cellspacing="0" cellpadding="0" width="100%">
<tr class="bg">
<td colspan="5" th:text="${table.tag}"></td>
</tr>
<tr>
<td width="25%">接口描述</td>
<td colspan="4" th:text="${table.description}"></td>
</tr>
<tr>
<td>URL</td>
<td colspan="4" th:text="${table.url}"></td>
</tr>
<tr>
<td>请求方式</td>
<td colspan="4" th:text="${table.requestType}"></td>
</tr>
<tr>
<td>请求类型</td>
<td colspan="4" th:text="${table.requestForm}"></td>
</tr>
<tr>
<td>返回类型</td>
<td colspan="4" th:text="${table.responseForm}"></td>
</tr>
<tr class="bg">
<td>参数名</td>
<td width="15%">数据类型</td>
<td width="15%">参数类型</td>
<td width="15%">是否必填</td>
<td width="29%">说明</td>
</tr>
<th:block th:each="request, c:${table.requestList}">
<tr>
<td align="left" th:text="${c.count} + '.' + ${request.name}"></td>
<td th:text="${request.type}"></td>
<td th:text="${request.paramType}"></td>
<td th:if="${request.require}" th:text="Y"></td>
<td th:if="${!request.require}" th:text="N"></td>
<td th:text="${request.remark}"></td>
<!-- <td th:if="${request.modelAttr}" th:text="asdfagadfg"></td>-->
</tr>
<th:block th:if="${request.modelAttr}">
<tbody th:include="this::request(${request.modelAttr.properties},${c.count} + '.', 1)"/>
</th:block>
</th:block>
<tr class="bg">
<td>状态码</td>
<td colspan="2">描述</td>
<td colspan="2">说明</td>
</tr>
<tr th:each="response:${table.responseList}">
<td th:text="${response.name}"></td>
<td colspan="2" th:text="${response.description}"></td>
<td colspan="2" th:text="${response.remark}"></td>
</tr>
<tr class="bg">
<td>返回属性名</td>
<td colspan="2">类型</td>
<td colspan="2">说明</td>
</tr>
<!-- 对返回参数 递归生成行-->
<tbody th:include="this::response(${table.modelAttr.properties},'', 1)"/>
<tr class="bg">
<td colspan="5">示例</td>
</tr>
<tr class="specialHeight">
<td class="bg">请求参数</td>
<td colspan="4" th:text="${table.requestParam}"></td>
</tr>
<tr class="specialHeight">
<td class="bg">返回值</td>
<td colspan="4" th:text="${table.responseParam}"></td>
</tr>
</table>
</div>
</div>
</div>
<th:block th:fragment="request(properties,count, lv)">
<th:block th:each="p,c : ${properties}">
<tr>
<td align="left" th:text="${count} + '' + ${c.count} + '.' + ${p.name}"
th:style="|padding-left:${10*lv}px|"></td>
<td th:text="${p.type}"></td>
<td></td>
<td th:if="${p.require}" th:text="Y"></td>
<td th:if="${!p.require}" th:text="N"></td>
<td th:text="${p.description}"></td>
</tr>
<th:block th:unless="${#lists.isEmpty(p.properties)}"
th:include="this::request(${p.properties},${count} + '' + ${c.count} + '.',${lv+1})"/>
</th:block>
</th:block>
<th:block th:fragment="response(properties,count, lv)">
<th:block th:each="p,c : ${properties}">
<tr>
<td align="left" th:text="${count} + '' + ${c.count} + '.' + ${p.name}"
th:style="|padding-left:${10*lv}px|"></td>
<td colspan="2" th:text="${p.type}"></td>
<td colspan="2" th:text="${p.description}"></td>
</tr>
<th:block th:unless="${#lists.isEmpty(p.properties)}"
th:include="this::response(${p.properties},${count} + '' + ${c.count} + '.',${lv+1})"/>
</th:block>
</th:block>
</body>
</html>

45
cdaxxt-business/pom.xml Normal file
View File

@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>integration-platform-access</artifactId>
<groupId>com.tobacco.mp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cdaxxt-business</artifactId>
<dependencies>
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>cdaxxt-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>cdaxxt-core</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,75 @@
package com.tobacco.mp.controller;
import com.alibaba.fastjson.JSONObject;
import com.tobacco.mp.dto.PlatformMessageDTO;
import com.tobacco.mp.dto.PlatformNoticeDTO;
import com.tobacco.mp.dto.PlatformTaskDTO;
import com.tobacco.mp.dto.PlatformTaskHandleDTO;
import com.tobacco.mp.service.PlatformMessageService;
import com.tobacco.mp.service.PlatformUserService;
import com.tobacco.mp.model.ResponseResult;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
// 一体化平台对接
@RestController
@AllArgsConstructor
@RequestMapping("/platform")
public class PlatformController {
@Resource
PlatformUserService userService;
@Resource
PlatformMessageService messageService;
// 查询一体化平台的用户列表
@GetMapping(value = "/getUserList")
public ResponseResult<Void> getUserList() {
userService.getUserList();
return ResponseResult.success();
}
// 查询一体化平台的用户ID
@GetMapping(value = "/getUserIdByAccount")
public ResponseResult<String> getUserIdByAccount(@RequestParam String loginName) {
return ResponseResult.success(userService.getUserIdByAccount(loginName));
}
// 一体化平台身份令牌认证
@GetMapping(value = "/tokenAccess")
public ResponseResult<JSONObject> tokenAccess(@RequestParam String token) {
return ResponseResult.success(userService.tokenAccess(token));
}
// 向一体化平台发送消息
@PostMapping(value = "/sendMessage")
public ResponseResult<Void> sendMessage(@RequestBody PlatformMessageDTO dataDTO) {
messageService.sendMessage(dataDTO);
return ResponseResult.success();
}
// 向一体化平台发送通知/公告
@PostMapping(value = "/sendNotice")
public ResponseResult<Void> sendNotice(@RequestBody PlatformNoticeDTO dataDTO) {
messageService.sendNotice(dataDTO);
return ResponseResult.success();
}
// 向一体化平台发送待办
@PostMapping(value = "/sendToDo")
public ResponseResult<Void> sendToDo(@RequestBody PlatformTaskDTO taskDTO) {
messageService.sendToDo(taskDTO);
return ResponseResult.success();
}
// 向一体化平台发送待办处置信息
@PostMapping(value = "/sendHandleToDo")
public ResponseResult<Void> sendHandleToDo(@RequestBody PlatformTaskHandleDTO handleDTO) {
messageService.sendHandleToDo(handleDTO);
return ResponseResult.success();
}
}

View File

@ -0,0 +1,47 @@
package com.tobacco.mp.dto;
import com.tobacco.mp.model.PlatformReceiverInfo;
import lombok.Data;
import java.util.List;
@Data
public class PlatformMessageDTO {
// 事件编码
private String eventCode;
// 消息类型,值范围: 10-系统消息 20-流程通知 30-赋能通知
private String msgType;
// 消息标题
private String msgTitle;
// 消息内容
private String msgContent;
// 消息链接
private String msgLink;
// 发送者名称
private String senderName;
// 发送者ID
private String senderId;
// 来源应用ID
private String fromAppId;
// 来源应用名称
private String fromAppName;
// 来源业务id
private String fromBusiId;
// 消息重要程度URGENT-紧急 IMPORTANT-重要 NORMAL-普通
private String msgPriority = "NORMAL";
// 消息接收人列表
private List<PlatformReceiverInfo> msgUserList;
}

View File

@ -0,0 +1,55 @@
package com.tobacco.mp.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class PlatformNoticeDTO {
// 公告标题*
private String title;
// 通知公告类型*
private String type;
// 公告来源* (PORTAL-门户维护API-系统接入)
private String source;
// 内容类型* (TEXT-文字内容LINK-跳转链接)
private String contentType;
// 公告内容*
private String content;
// 跳转链接url*
private String linkUrl;
// 发布方式* (IMMEDIATE:立即发布;SCHEDULE:定时发布)
private String publishType;
// 定时发布时间*
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date scheduleTime;
// 有效期类型* (PERMANENT-永久有效TEMPORARY-非永久有效)
private String expiryType;
// 有效期截止时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date expiryDate;
// 可见范围类型* (ALL-全省可见,CITY:全市可见DEPT-下级组织可见)
private String visibleType;
// 创建人名称*
private String creatorName;
// 创建人用户id*
private String creatorId;
// 应用id*
private String clientId;
}

View File

@ -0,0 +1,92 @@
package com.tobacco.mp.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
import java.util.List;
@Data
public class PlatformTaskDTO {
// 任务名称*
private String taskName;
// 任务描述*
private String taskDesc;
// 业务主键*
private String businessId;
// 需要关联的流程实例
private String processId;
// 需要关联的流程名称
private String processName;
// 会签分组标记,用于记录任务所属的会签分组,也可用于其他分组(按需维护)
private String taskCollaborateId;
// 需要关联的流程任务实例
private String processTaskId;
// 待办类型 (字典TTC_TODO_TYPE)
private String todoType;
// 业务类型
private String bizType;
// 紧急程度* (1高2中3低)
private int todoPriority = 2;
// 中台消息中心的模板编码,发通知消息时,未指定模板则使用该默认模板
private String eventCode;
// 上级任务ID有撤回场景时需要维护
private String preTaskId;
// 创建人账号ID*
private String createUserId;
// 是否开始节点
private Boolean isStart;
// 是否结束节点
private Boolean isEnd;
// 相关附件
private List<String> attachmentPath;
// 系统需要在业务中台AppId* (用户中心完成应用系统注册得到appId)
private String createAppId;
//系统需要在业务中台AppId* (用户中心完成应用系统注册得到appId)
private String handleAppId;
// 任务处理地址*
private String optAddress;
// 移动任务处理地址,模糊查询*
private String optAddressMobile;
// 拓展属性配置
private String extraConfig;
// 处理截止时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date deadline;
// 移交前任务ID
private String translateOriginId;
// 创建时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date gmtCreate;
// 操作人ID*
private String optUserId;
// 操作人名称
private String optUserName;
}

View File

@ -0,0 +1,50 @@
package com.tobacco.mp.dto;
import lombok.Data;
import java.util.List;
import java.util.Map;
@Data
public class PlatformTaskHandleDTO {
// 待办任务ID*
private String todoTaskId;
// 实际处理人ID*
private String handleUserId;
// 相关附件
private List<String> attachmentPath;
// 处理结果字典TTC_TASK_OPT_RESULT
private String optResult;
// 处理意见
private String optComment;
// 操作人ID*
private String optUserId;
// 操作人名称
private String optUserName;
// 是否发送待办通知 (false或null则根据任务自动通知配置情况发送消息)
private Boolean sendNotification;
// 中台消息模板,发送通知时有效,不传值则使用任务设置的默认模板
private String eventCode;
// 消息接收人
private String receiverId;
// 消息额外参数,不同消息类型的个性化参数与模板的动态参数
private Map<String, String> extraProps;
// 任务处理地址
private String optAddress;
// 移动任务处理地址,模糊查询
private String optAddressMobile;
}

View File

@ -0,0 +1,202 @@
package com.tobacco.mp.entity;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
@Data
@Accessors(chain = true)
@TableName(value = "sys_user")
public class SysUser implements Serializable {
@TableField(exist = false)
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.INPUT)
@ApiModelProperty(value = "用户ID")
private String id;
@TableField(value = "position_type")
@ApiModelProperty(value = "岗位类型")
private String positionType;
@TableField(value = "position_id")
@ApiModelProperty(value = "岗位ID")
private String positionId;
@TableField(value = "position_name")
@ApiModelProperty(value = "岗位名称")
private String positionName;
@TableField(value = "is_virtual_user")
@ApiModelProperty(value = "是否虚拟用户1、是 2、不是")
private String isVirtualUser;
@TableField(value = "login_name")
@ApiModelProperty(value = "登录账号")
private String loginName;
@TableField(value = "password")
@ApiModelProperty(value = "密码")
private String password;
@TableField(value = "user_name")
@ApiModelProperty(value = "用户昵称")
private String userName;
@TableField(value = "user_type")
@ApiModelProperty(value = "用户类型00系统用户 01注册用户")
private String userType;
@TableField(value = "email")
@ApiModelProperty(value = "用户邮箱")
private String email;
@TableField(value = "mobile", updateStrategy = FieldStrategy.IGNORED)
@ApiModelProperty(value = "移动电话")
private String mobile;
@TableField(value = "tele_phone", updateStrategy = FieldStrategy.IGNORED)
@ApiModelProperty(value = "电话号码")
private String telePhone;
@TableField(value = "id_entity_card")
@ApiModelProperty(value = "身份证号")
private String idEntityCard;
@TableField(value = "in_dust_rial_id")
@ApiModelProperty(value = "行业号码(如:警号)")
private String inDustRialId;
@TableField(value = "sex")
@ApiModelProperty(value = "用户性别0男 1女 2未知")
private String sex;
@TableField(value = "nation", updateStrategy = FieldStrategy.IGNORED)
@ApiModelProperty(value = "民族")
private String nation;
@TableField(value = "politic", updateStrategy = FieldStrategy.IGNORED)
@ApiModelProperty(value = "政治面貌")
private String politic;
@TableField(value = "marital")
@ApiModelProperty(value = "婚姻状态")
private String marital;
@TableField(value = "type")
@ApiModelProperty(value = "人员类别")
private String type;
@TableField(value = "type_name")
@ApiModelProperty(value = "人员类别中文")
private String typeName;
@TableField(value = "whcd", updateStrategy = FieldStrategy.IGNORED)
@ApiModelProperty(value = "文化程度")
private String whcd;
@TableField(value = "user_no", updateStrategy = FieldStrategy.IGNORED)
@ApiModelProperty(value = "排序")
private Integer userNo;
@TableField(value = "bz", updateStrategy = FieldStrategy.IGNORED)
@ApiModelProperty(value = "备注")
private String bz;
@TableField(value = "birthday")
@ApiModelProperty(value = "出生日期")
private String birthday;
@TableField(value = "begin_time")
@ApiModelProperty(value = " 用户有效开始时间,默认为当前日期(用户可改)")
private Date beginTime;
@TableField(value = "end_time")
@ApiModelProperty(value = " 用户有效结束时间,默认空")
private Date endTime;
@TableField(value = "salt")
@ApiModelProperty(value = "盐加密")
private String salt;
@TableField("duty_code")
@ApiModelProperty("职务code")
private String dutyCode;
@TableField("duty_name")
@ApiModelProperty("职务名称")
private String dutyName;
@TableField("outsourcing_level")
@ApiModelProperty("D_BZ_ZYWHRYLB-聘用人员类别 1.在岗在册 2.劳务派遣 3.业务外包")
private String outsourcingLevel;
@TableField("long_term_sick_leave")
@ApiModelProperty(" 是否长期病假人员")
private String longTermSickLeave;
@TableField("platform_user_id")
@ApiModelProperty(" 业务中台用户ID")
private String platformUserId;
@TableField(value = "xzcs")
@ApiModelProperty(value = "选择次数")
private Integer xzcs;
@TableField(value = "xt_zxbz")
private Integer xtZxbz;
@TableField(value = "xt_zxyz")
private String xtZxyz;
@TableField(value = "xt_cjsj")
private Date xtCjsj;
@TableField(value = "xt_lrsj")
private Date xtLrsj;
@TableField(value = "xt_lrrxm")
private String xtLrrxm;
@TableField(value = "xt_lrrid")
private String xtLrrid;
@TableField(value = "xt_lrrbm")
private String xtLrrbm;
@TableField(value = "xt_lrrbmid")
private String xtLrrbmid;
@TableField(value = "xt_lrip")
private String xtLrip;
@TableField(value = "xt_zhxgsj")
private Date xtZhxgsj;
@TableField(value = "xt_zhxgrxm")
private String xtZhxgrxm;
@TableField(value = "xt_zhxgid")
private String xtZhxgid;
@TableField(value = "xt_zhxgrbm")
private String xtZhxgrbm;
@TableField(value = "xt_zhxgrbmid")
private String xtZhxgrbmid;
@TableField(value = "xt_zhxgrip")
private String xtZhxgrip;
@TableField(value = "xt_city_code")
private String xtCityCode;
@TableField(value = "xt_city_name")
private String xtCityName;
}

View File

@ -0,0 +1,22 @@
package com.tobacco.mp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tobacco.mp.entity.SysUser;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface SysUserMapper extends BaseMapper<SysUser> {
// 获取业务中台用户ID为空的用户账号列表
List<String> getNullPlatformUserId();
// 给用户绑定业务中台的用户ID
void setPlatformUserId(@Param("userName") String userName, @Param("platformUserId") String platformUserId);
// 更新任务的一体化平台ID
void updateRwPlatformId(@Param("rwId") String rwId, @Param("platformId") String platformId);
}

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tobacco.mp.mapper.SysUserMapper">
<!--获取业务中台用户ID为空的用户账号列表-->
<select id="getNullPlatformUserId" resultType="java.lang.String">
SELECT user_name FROM mosty_base_gs.sys_user WHERE xt_zxbz = 0 AND platform_user_id IS NULL
</select>
<!--给用户绑定业务中台的用户ID-->
<update id="setPlatformUserId">
UPDATE mosty_base_gs.sys_user SET platform_user_id = #{platformUserId} WHERE user_name = #{userName}
</update>
<!--给用户绑定业务中台的用户ID-->
<update id="updateRwPlatformId">
UPDATE mosty_jcgl_gs.tb_rw SET platform_id = #{platformId} WHERE id = #{rwId}
</update>
</mapper>

View File

@ -0,0 +1,14 @@
package com.tobacco.mp.model;
import lombok.Data;
@Data
public class PlatformReceiverInfo {
// 接收者名称
private String receiverName;
// 接收者ID
private String receiverId;
}

View File

@ -0,0 +1,23 @@
package com.tobacco.mp.model;
/**
* 一体化平台响应状态码
*/
public class PlatformResponseCode {
// 成功
public static final String SUCCESS = "200";
// 未授权
public static final String UNAUTHORIZED = "401";
// 禁止访问
public static final String ACCESS_DENIED = "403";
// 资源不存在
public static final String NOT_EXIST = "404";
// 服务异常
public static final String SERVICE_EXCEPTION = "500";
}

View File

@ -0,0 +1,136 @@
package com.tobacco.mp.service;
import com.alibaba.bizworks.core.runtime.common.SingleResponse;
import com.tobacco.mp.dto.PlatformMessageDTO;
import com.tobacco.mp.dto.PlatformNoticeDTO;
import com.tobacco.mp.dto.PlatformTaskDTO;
import com.tobacco.mp.dto.PlatformTaskHandleDTO;
import com.tobacco.mp.mcext.client.api.McExtNoticeServiceAPI;
import com.tobacco.mp.mcext.client.api.MessageSendExtServiceAPI;
import com.tobacco.mp.mcext.client.api.message.dto.SendMessageDTO;
import com.tobacco.mp.mcext.client.api.message.req.SendInternalMessageRequest;
import com.tobacco.mp.mcext.client.api.notice.dto.CreateNoticeResponse;
import com.tobacco.mp.mcext.client.api.notice.req.CreateNoticeRequest;
import com.tobacco.mp.model.PlatformResponseCode;
import com.tobacco.mp.ttc.client.api.TodoTaskApi;
import com.tobacco.mp.ttc.client.api.enums.TaskHandleTargetTypeEnum;
import com.tobacco.mp.ttc.client.api.task.dto.TodoTaskDTO;
import com.tobacco.mp.ttc.client.api.task.req.CreateTaskRequest;
import com.tobacco.mp.ttc.client.api.task.req.SubmitTaskRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class PlatformMessageService {
@Resource
private MessageSendExtServiceAPI messageSendExtServiceAPI;
@Resource
private McExtNoticeServiceAPI mcExtNoticeServiceAPI;
@Resource
private TodoTaskApi todoTaskApi;
@Resource
private SysUserService sysUserService;
@Value("${bizworks.clientId}")
private String clientId;
/**
* 发送消息
* @param messageDTO
*/
public void sendMessage(PlatformMessageDTO messageDTO) {
// 构建消息请求参数
SendInternalMessageRequest request = new SendInternalMessageRequest();
BeanUtils.copyProperties(messageDTO, request, "msgUserList");
request.setFromAppId(clientId);
request.setFromAppName("安管平台应用");
List<SendInternalMessageRequest.ReceiverInfo> msgUserList = new ArrayList<>();
BeanUtils.copyProperties(messageDTO.getMsgUserList(), msgUserList);
request.setMsgUserList(msgUserList);
// 发送消息请求
SingleResponse<SendMessageDTO> response = messageSendExtServiceAPI.sendInternalMessage(request);
if (response.getCode().equals(PlatformResponseCode.SUCCESS)) {
log.info("消息【{}】请求处理成功", messageDTO.getMsgTitle());
} else {
log.error("消息【{}】请求处理失败。失败原因:{}", messageDTO.getMsgTitle(), response.getMessage());
}
}
/**
* 发送通知/公告
* @param noticeDTO
*/
public void sendNotice(PlatformNoticeDTO noticeDTO) {
// 构建通知/公告请求参数
CreateNoticeRequest request = new CreateNoticeRequest();
BeanUtils.copyProperties(noticeDTO, request);
request.setSource("API");
request.setClientId(clientId);
// 发送通知/公告请求
SingleResponse<CreateNoticeResponse> response = mcExtNoticeServiceAPI.createNotice(request);
if (response.getCode().equals(PlatformResponseCode.SUCCESS)) {
log.info("通知【{}】请求处理成功", noticeDTO.getTitle());
} else {
log.error("通知【{}】请求处理失败。失败原因:{}", noticeDTO.getTitle(), response.getMessage());
}
}
/**
* 创建待办任务
* @param taskDTO
*/
public void sendToDo(PlatformTaskDTO taskDTO) {
// 构建待办任务请求参数
CreateTaskRequest request = new CreateTaskRequest();
BeanUtils.copyProperties(taskDTO, request);
request.setHandleTargetId(taskDTO.getOptUserId());
request.setHandleTargetType(TaskHandleTargetTypeEnum.USER);
request.setCreateAppId(clientId);
request.setHandleAppId(clientId);
// 发送待办任务请求
SingleResponse<TodoTaskDTO> response = todoTaskApi.createTask(request);
if (response.getCode().equals(PlatformResponseCode.SUCCESS)) {
TodoTaskDTO todoTaskDTO = response.getData();
if (todoTaskDTO != null && StringUtils.isNotEmpty(todoTaskDTO.getId())) {
sysUserService.updateRwPlatformId(taskDTO.getBusinessId(), todoTaskDTO.getId());
}
log.info("待办【{}】请求处理成功", taskDTO.getTaskName());
} else {
log.error("待办【{}】请求处理失败。失败原因:{}", taskDTO.getTaskName(), response.getMessage());
}
}
/**
* 处置待办
* @param handleDTO
*/
public void sendHandleToDo(PlatformTaskHandleDTO handleDTO) {
// 处置待办参数校验
if (StringUtils.isEmpty(handleDTO.getTodoTaskId())) {
return;
}
// 构建处置待办请求参数
SubmitTaskRequest request = new SubmitTaskRequest();
BeanUtils.copyProperties(handleDTO, request);
// 发送处置待办请求
SingleResponse<Boolean> response = todoTaskApi.submitTask(request);
if (response.getCode().equals(PlatformResponseCode.SUCCESS)) {
log.info("待办处理【{}】请求处理成功", handleDTO.getTodoTaskId());
} else {
log.error("待办处理【{}】请求处理失败。失败原因:{}", handleDTO.getTodoTaskId(), response.getMessage());
}
}
}

View File

@ -0,0 +1,127 @@
package com.tobacco.mp.service;
import com.alibaba.bizworks.core.runtime.common.MultiDataDTO;
import com.alibaba.bizworks.core.runtime.common.MultiResponse;
import com.alibaba.bizworks.core.runtime.common.SingleResponse;
import com.alibaba.fastjson.JSONObject;
import com.tobacco.mp.auth.businessdomain.auth.client.api.SsoAuthI;
import com.tobacco.mp.auth.businessdomain.auth.client.api.auth.dto.TokenCheckResultDTO;
import com.tobacco.mp.auth.businessdomain.auth.client.api.auth.req.CheckTokenRequest;
import com.tobacco.mp.constant.Constant;
import com.tobacco.mp.model.PlatformResponseCode;
import com.tobacco.mp.uc.client.api.UserServiceAPI;
import com.tobacco.mp.uc.client.api.user.dto.GetUserByUserCodeDTO;
import com.tobacco.mp.uc.client.api.user.dto.UserDTO;
import com.tobacco.mp.uc.client.api.user.req.GetUserByUserCodeRequest;
import com.tobacco.mp.uc.client.api.user.req.PageQueryUserRequest;
import com.tobacco.mp.utils.JWTUtil;
import com.tobacco.mp.utils.RandomUtil;
import com.tobacco.mp.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
@Slf4j
@Service
public class PlatformUserService {
@Resource
private UserServiceAPI userServiceAPI;
@Resource
private SsoAuthI ssoAuthI;
@Resource
private RedisUtils redisUtils;
@Value("${bizworks.clientId}")
private String clientId;
/**
* 查询一体化平台的用户ID
* @param loginName
* @return
*/
public String getUserIdByAccount(String loginName) {
// 构建查询平台用户请求参数
GetUserByUserCodeRequest request = new GetUserByUserCodeRequest();
request.setUserCode(loginName);
// 发送查询平台用户请求
SingleResponse<GetUserByUserCodeDTO> response = userServiceAPI.getUserByUserCode(request);
if (response.getCode().equals(PlatformResponseCode.SUCCESS)) {
GetUserByUserCodeDTO userDTO = response.getData();
if (userDTO != null && StringUtils.isNotEmpty(userDTO.getUserId())) {
return userDTO.getUserId();
}
} else {
log.error("获取中台用户[{}]请求处理失败。失败原因:{}", loginName, response.getMessage());
}
return null;
}
/**
* 查询一体化平台的用户列表
*/
public void getUserList() {
// 构建查询平台用户列表请求参数
PageQueryUserRequest request = new PageQueryUserRequest();
request.setPageNumber(1);
request.setPageSize(10);
request.setManageUnitId("12");
// 发送查询平台用户列表请求
MultiResponse<UserDTO> response = userServiceAPI.pageQueryUser(request);
if (response.getCode().equals(PlatformResponseCode.SUCCESS)) {
MultiDataDTO<UserDTO> userDTO = response.getData();
if (userDTO != null && !CollectionUtils.isEmpty(userDTO.getItems())) {
for (UserDTO user : userDTO.getItems()) {
System.out.println("userId:" + user.getUserId() + ", userName:" + user.getLoginName());
}
}
} else {
log.error("分页获取中台用户请求处理失败。失败原因:{}", response.getMessage());
}
}
/**
* 校验本系统登录页面的token(一体化平台的token)信息
* @param token
* @return
*/
public JSONObject tokenAccess(String token) {
// 声明响应数据(用户名和系统登录校验码)
JSONObject jsonObject = new JSONObject();
String account = "";
// 给一体化平台发送解析请求以验证令牌获取用户名
SingleResponse<TokenCheckResultDTO> singleResponse = ssoAuthI.checkToken(new CheckTokenRequest(token, clientId));
if (singleResponse.getCode().equals(PlatformResponseCode.SUCCESS)) {
TokenCheckResultDTO data = singleResponse.getData();
if (data != null && StringUtils.isNotEmpty(data.getUserInfo())) {
Claims claims = JWTUtil.verifyJWTToken(data.getUserInfo(), JWTUtil.PUBLIC_KEY_STR);
account = claims.get("account", String.class);
} else {
log.error("请求一体化平台响应数据:{}", JSONObject.toJSONString(data));
return jsonObject;
}
} else {
log.error("鉴权请求处理失败。失败原因:{}", singleResponse.getMessage());
return jsonObject;
}
// 验证通过后,给页面返回用户名和本系统登录校验码
if (StringUtils.isNotEmpty(account)) {
String verifyCode = RandomUtil.generateLowerString(16);
redisUtils.set(Constant.LOGIN_VERIFY_CODE + account, verifyCode, 30);
jsonObject.put("userName", account);
jsonObject.put("verifyCode", verifyCode);
log.info("--------一体化平台成功鉴权!----------");
}
return jsonObject;
}
}

View File

@ -0,0 +1,30 @@
package com.tobacco.mp.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class SchedulerService {
@Resource
SysUserService sysUserService;
@Resource
PlatformUserService platformUserService;
/**
* 刷新用户业务中台的ID
*/
// @Scheduled(cron = "0 0 3 * * ?")
public void refreshUserPlatformId() {
List<String> userNames = sysUserService.getNullPlatformUserId();
for (String userName : userNames) {
String platformUserId = platformUserService.getUserIdByAccount(userName);
sysUserService.setPlatformUserId(userName, platformUserId);
}
}
}

View File

@ -0,0 +1,39 @@
package com.tobacco.mp.service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tobacco.mp.entity.SysUser;
import com.tobacco.mp.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> {
/**
* 获取业务中台用户ID为空的用户账号列表
* @return
*/
public List<String> getNullPlatformUserId() {
return this.baseMapper.getNullPlatformUserId();
}
/**
* 给用户绑定业务中台的用户ID
* @param userName
* @param platformUserId
*/
public void setPlatformUserId(String userName, String platformUserId) {
this.baseMapper.setPlatformUserId(userName, platformUserId);
}
/**
* 更新任务的一体化平台ID
* @param rwId
* @param platformId
*/
public void updateRwPlatformId(String rwId, String platformId) {
this.baseMapper.updateRwPlatformId(rwId, platformId);
}
}

32
cdaxxt-common/pom.xml Normal file
View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>integration-platform-access</artifactId>
<groupId>com.tobacco.mp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cdaxxt-common</artifactId>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,14 @@
package com.tobacco.mp.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 【允许已登录的社会用户访问的接口】使用该注解(无效)
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthOperation {
}

View File

@ -0,0 +1,14 @@
package com.tobacco.mp.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 【需要记录操作日志】使用该注解
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogOperation {
}

View File

@ -0,0 +1,14 @@
package com.tobacco.mp.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 【需要开放第三方对接的接口】使用该注解
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface OpenOperation {
}

View File

@ -0,0 +1,14 @@
package com.tobacco.mp.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 【不需要登录就能访问的接口】使用该注解
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassOperation {
}

View File

@ -0,0 +1,24 @@
package com.tobacco.mp.constant;
/**
* 基础常量信息
*/
public class Constant {
/********************************************缓存key***********************************************/
public static final String LOGIN_VERIFY_CODE = "LoginVerifyCode:";
public static final String JWT_USER = "JwtUser:";
/*************************************************************************************************/
public static final String DEFAULT_IP = "0.0.0.0";
/** 开放的API */
public static final String OPEN_API = "OPENAPI";
/** 开放的应用 */
public static final String OPEN_APP = "OPENAPP";
}

View File

@ -0,0 +1,35 @@
package com.tobacco.mp.constant;
/**
* @Author XiongLiJian
* @Date 2021/6/4 9:31
* @Description 符号工具类
* @Version 1.0
**/
public class Symbol {
/** 符号:[-] */
public static final String ACROSS = "-";
/** 符号:[_] */
public static final String LOW_ACROSS = "_";
/** 符号[.] */
public static final String POINT = ".";
/** 符号[:] */
public static final String COLON = ":";
/** 逗号[,] */
public static final String COMMA = ",";
/** 斜杠 */
public static final String SLASH = "/";
/** 逗号[@] */
public static final String A2 = "@";
/** 符号[;] */
public static final String SEMICOLON = ";";
}

View File

@ -0,0 +1,48 @@
package com.tobacco.mp.enums;
/**
* 响应码管理
* @Author: XiongLiJian
* @Date: 2020/12/29 09:14
*/
public enum ResponseCodeEnum {
NORMAL(200, "ok"),
REQUEST_PARAM_ERROR(400, "请求参数错误!"),
SYSTEM_NO_LOGIN(401, "系统未登录!"),
USER_ALREADY_DISABLED(402, "该用户已被禁用!"),
NO_ACCESS_PERMISSION(403, "没有访问权限!"),
REQUEST_RESOURCE_NO_EXIST(404, "请求的资源不存在!"),
REQUEST_METHOD_ERROR(405, "请求方式错误"),
SYSTEM_ERROR(500, "系统错误"),
SYSTEM_TIP(501, "系统提示"),
;
/** 响应码 */
private Integer code;
/** 响应信息 */
private String msg;
ResponseCodeEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}

View File

@ -0,0 +1,41 @@
package com.tobacco.mp.enums;
/**
* @Author XiongLiJian
* @Date 2021/12/29 9:25
* @Description 消息提示
* @Version 1.0
**/
public enum TipEnum {
BATCH_DELETE_DATA_ERROR("批量删除解析错误!"),
FILE_NOT_SURE("请指定一个文件进行操作!"),
SYSTEM_ERROR("系统出现错误!"),
USERNAME_NOT_EXIST("用户名不存在!"),
PLEASE_WAIT_REPEAT_LOGIN("该账号今天重复多次密码错误请30分钟后重新登录"),
ACCOUNT_PASSWORD_ERROR("账号或密码错误!"),
ACCESS_FILE_ERROR("权限模板文件解析异常!"),
ACCESS_API_ERROR("权限映射解析异常!"),
ROLE_PERSON_NUM_EXSIT("角色下存在人员无法删除!"),
DATA_SHEET_IMPORT_ERROR("数据导入解析错误!"),
USERNAME_IS_REPEAT("该用户名已存在!"),
NOT_MODIFY_SYSTEM_ROLE("不能操作系统超级管理员!"),
CHECK_CODE_REPEAT("请不要频繁生成校验码!"),
;
private String msg;
TipEnum(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}

View File

@ -0,0 +1,32 @@
package com.tobacco.mp.exception;
import com.tobacco.mp.enums.ResponseCodeEnum;
import com.tobacco.mp.enums.TipEnum;
import lombok.Data;
/**
* @Author XiongLiJian
* @Date 2021/6/3 17:53
* @Description 服务器异常
* @Version 1.0
**/
@Data
public class ServiceException extends RuntimeException {
private static final long serialVersionUID = 6165589759025169495L;
private Integer code = ResponseCodeEnum.SYSTEM_TIP.getCode();
private String message;
public ServiceException(TipEnum tipEnum) {
super(tipEnum.getMsg());
this.message = tipEnum.getMsg();
}
public ServiceException(String message) {
super(message);
this.message = message;
}
}

View File

@ -0,0 +1,54 @@
package com.tobacco.mp.model;
import com.tobacco.mp.enums.ResponseCodeEnum;
import lombok.Data;
@Data
public class Json<T> {
private boolean success;
private Integer code;
private String message;
private T data;
public static Json success() {
return success(null);
}
public static Json success(Object data) {
Json json = new Json();
json.setSuccess(true);
json.setCode(ResponseCodeEnum.NORMAL.getCode());
json.setMessage(ResponseCodeEnum.NORMAL.getMsg());
json.setData(data);
return json;
}
public static Json fail(ResponseCodeEnum responseCodeEnum) {
Json json = new Json();
json.setSuccess(false);
json.setCode(responseCodeEnum.getCode());
json.setMessage(responseCodeEnum.getMsg());
return json;
}
public static Json fail(Integer code, String message) {
Json json = new Json();
json.setCode(code);
json.setMessage(message);
json.setSuccess(false);
return json;
}
public static Json fail(String message) {
Json json = new Json();
json.setCode(ResponseCodeEnum.SYSTEM_TIP.getCode());
json.setMessage(message);
json.setSuccess(false);
return json;
}
}

View File

@ -0,0 +1,93 @@
package com.tobacco.mp.model;
import lombok.Data;
import java.io.Serializable;
import java.util.Objects;
@Data
@SuppressWarnings("unused")
public class ResponseResult<T> implements Serializable {
/** 调用成功编码 */
private static final int SUCCESS_CODE = 10000;
/** 调用失败编码 */
private static final int FAIL_CODE = -1;
/** 编号 */
private int code = SUCCESS_CODE;
/** 消息 */
private String message;
/** 数据 */
private T data;
public ResponseResult() {
}
public ResponseResult(T data) {
this.message = "OK";
this.data = data;
}
public ResponseResult(int code, String msg) {
this.code = code;
this.message = msg;
this.data = null;
}
public ResponseResult(int code, String msg, T data) {
this.code = code;
this.message = msg;
this.data = data;
}
public static <T> ResponseResult<T> success() {
return new ResponseResult(SUCCESS_CODE, "OK", null);
}
public static <T> ResponseResult<T> success(int code, String message, T data) {
return new ResponseResult(code, message, data);
}
public static <T> ResponseResult<T> success(String message, T data) {
return new ResponseResult(SUCCESS_CODE, message, data);
}
public static <T> ResponseResult<T> success(T data) {
return new ResponseResult(SUCCESS_CODE, "OK", data);
}
public static <T> ResponseResult<T> fail(String message) {
return new ResponseResult(FAIL_CODE, message, (Object)null);
}
public static <T> ResponseResult<T> fail(int code, String message) {
return new ResponseResult(code, message, (Object)null);
}
public static <T> ResponseResult<T> fail(int code, String message, T t) {
return new ResponseResult(code, message, t);
}
public boolean isSuccess() {
return SUCCESS_CODE == code;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) {
return false;
}
ResponseResult<?> that = (ResponseResult<?>) o;
return Objects.equals(code, that.code) && Objects.equals(message, that.message) && Objects.equals(data, that.data);
}
@Override
public int hashCode() {
return Objects.hash(code, message, data);
}
}

View File

@ -0,0 +1,172 @@
package com.tobacco.mp.utils;
import com.tobacco.mp.annotation.AuthOperation;
import com.tobacco.mp.annotation.OpenOperation;
import com.tobacco.mp.annotation.PassOperation;
import com.tobacco.mp.constant.Constant;
import com.tobacco.mp.constant.Symbol;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import java.lang.reflect.Method;
import java.util.*;
@Slf4j
@Component
public class AnnotationUtil {
@Autowired
RedisUtils redisUtils;
private final String RESOURCE_PATTERN = "com/tobacco/mp/**/controller/*.class";
public static List<String> PASS_API;
public static List<String> AUTH_API;
/**
* 加载自定义注解
*/
public void loadCustomAnnotation() {
Map<String, List<String>> mapApis = getAccessAnnotations(RESOURCE_PATTERN);
// 获取开放给第三方的接口数据
if (mapApis.get(OpenOperation.class.getName()) != null) {
redisUtils.set(Constant.OPEN_API, StringUtils.toString(mapApis.get(OpenOperation.class.getName())));
}
// 不需要登录就能访问的接口
PASS_API = mapApis.get(PassOperation.class.getName());
if (PASS_API == null) {
PASS_API = new ArrayList<>();
}
// 允许已登录的社会用户访问的接口
AUTH_API = mapApis.get(AuthOperation.class.getName());
if (AUTH_API == null) {
AUTH_API = new ArrayList<>();
}
}
/**
* 获取指定路径下OpenOperation注解下的uri接口
* @return
*/
private Map<String, List<String>> getAccessAnnotations(String resourcePattern) {
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
Map<String, List<String>> map = new HashMap<>();
try {
String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourcePattern;
Resource[] resources = resourcePatternResolver.getResources(pattern);
MetadataReaderFactory readerfactory = new CachingMetadataReaderFactory(resourcePatternResolver);
for (Resource resource : resources) {
// 读取类信息
MetadataReader reader = readerfactory.getMetadataReader(resource);
// 扫描到的class
String classname = reader.getClassMetadata().getClassName();
Class<?> clazz = Class.forName(classname);
Method[] methods = clazz.getMethods();
for (Method method: methods) {
OpenOperation openAnno = method.getAnnotation(OpenOperation.class);
// 判断是否有指定主解
if (openAnno != null) {
// 获取注解的方法与接口请求注解
String api = getApi(clazz, method);
List<String> openApi = map.get(OpenOperation.class.getName());
if (CollectionUtils.isEmpty(openApi)) {
openApi = new ArrayList<>();
map.put(OpenOperation.class.getName(), openApi);
}
openApi.add(api);
}
AuthOperation authAnno = method.getAnnotation(AuthOperation.class);
// 判断是否有指定主解
if (authAnno != null) {
// 获取注解的方法与接口请求注解
String api = getApi(clazz, method);
List<String> authApi = map.get(AuthOperation.class.getName());
if (CollectionUtils.isEmpty(authApi)) {
authApi = new ArrayList<>();
map.put(AuthOperation.class.getName(), authApi);
}
authApi.add(api);
}
PassOperation passAnno = method.getAnnotation(PassOperation.class);
// 判断是否有指定主解
if (passAnno != null) {
// 获取注解的方法与接口请求注解
String api = getApi(clazz, method);
List<String> passApi = map.get(PassOperation.class.getName());
if (CollectionUtils.isEmpty(passApi)) {
passApi = new ArrayList<>();
map.put(PassOperation.class.getName(), passApi);
}
passApi.add(api);
}
}
}
} catch (Exception e) {
}
return map;
}
/**
* 获取api接口
* @param
* @param
*/
private String getApi(Class<?> clazz, Method method) {
RequestMapping request = clazz.getDeclaredAnnotation(RequestMapping.class);
if (request != null) {
String api = request.value().length > 0 ? request.value()[0] : "";
if (!api.contains(Symbol.SLASH)) {
api = Symbol.SLASH + api;
}
String name = "";
// 获取方法的接口路由
GetMapping getAnn = method.getAnnotation(GetMapping.class);
if (getAnn != null) {
name = getAnn.value().length > 0 ? getAnn.value()[0] : "";
if (!name.contains(Symbol.SLASH)) {
name = Symbol.SLASH + name;
}
}
PostMapping postAnn = method.getAnnotation(PostMapping.class);
if (postAnn != null) {
name = postAnn.value().length > 0 ? postAnn.value()[0] : "";
if (!name.contains(Symbol.SLASH)) {
name = Symbol.SLASH + name;
}
}
DeleteMapping deleteAnn = method.getAnnotation(DeleteMapping.class);
if (deleteAnn != null) {
name = deleteAnn.value().length > 0 ? deleteAnn.value()[0] : "";
if (!name.contains(Symbol.SLASH)) {
name = Symbol.SLASH + name;
}
}
PutMapping putAnn = method.getAnnotation(PutMapping.class);
if (putAnn != null) {
name = putAnn.value().length > 0 ? putAnn.value()[0] : "";
if (!name.contains(Symbol.SLASH)) {
name = Symbol.SLASH + name;
}
}
api += name;
return api;
}
return UUID.randomUUID().toString();
}
}

View File

@ -0,0 +1,108 @@
package com.tobacco.mp.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class JWTUtil {
// 公钥
public static String PUBLIC_KEY_STR = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwHOi7T3dx95MADXlRPkLeFS+08f7dGg6RxbG5gug+yQLnw1ARNDYx6zK0gtHU+qmUlBCVqHS5vqAt73ydDKUGY9IgdMcxWtbPj456wF7W86xDv6EfiV/G9ZRVvPWmgNUxw1RXtQa91sIuyCxp4xIFd43wROxWUbmN+Omiv2ZYqYBquSdmzslL1dDypPCZ53ZCs1aY6TodbhndySp8E7YAhw8o+F2uGPW9p1Xz1w4hIZBo10b49rOpR5h0t2U4OloBbAC8Too6Smb5ZdYseUZLLD+PW1O0l7uMBlmJuqjPXRUxuTwXUO+EA4Z/ymBXalE4Zi3uEomISqWajSDPOG4pwIDAQAB";
/**
* 从Base64编码的字符串加载公钥
* @param publicKeyStr Base64编码的公钥字符串
* @return PublicKey对象
*/
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
// 移除PEM格式的标记
String publicKeyPEM = publicKeyStr
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s", "");
// Base64解码
byte[] encoded = Base64.getDecoder().decode(publicKeyPEM);
// 创建公钥规范
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
// 根据算法获取KeyFactory
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(keySpec);
}
/**
* 验证JWT令牌
* @param token JWT令牌字符串
* @param publicKey 公钥
* @return Claims 声明信息
*/
public static Claims verifyJWT(String token, PublicKey publicKey) {
return Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token).getBody();
}
/**
* 验证令牌签名信息
* @param token 令牌
* @param publicKeyStr 公钥字符串
* @return
*/
public static Claims verifyJWTToken(String token, String publicKeyStr) {
try {
// 加载公钥
PublicKey publicKey = loadPublicKey(publicKeyStr);
// 验证JWT
return Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(token).getBody();
} catch (io.jsonwebtoken.security.SignatureException e) {
throw new RuntimeException("无效的签名", e);
} catch (io.jsonwebtoken.ExpiredJwtException e) {
throw new RuntimeException("令牌已过期", e);
} catch (io.jsonwebtoken.MalformedJwtException e) {
throw new RuntimeException("无效的令牌格式", e);
} catch (Exception e) {
throw new RuntimeException("令牌验证失败", e);
}
}
/**
* 读取txt文件的内容
* @param file 想要读取的文件对象
* @return 返回文件内容
*/
public static String readTxt(File file) {
StringBuilder result = new StringBuilder();
try {
// 构造一个BufferedReader类来读取文件
BufferedReader br = new BufferedReader(new FileReader(file));
String s = null;
// 使用readLine方法一次读一行
while ((s = br.readLine()) != null) {
result.append(System.lineSeparator()+s);
}
br.close();
} catch(Exception e) {
e.printStackTrace();
}
return result.toString();
}
public static void main(String[] args) {
String publicKeyStr = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwHOi7T3dx95MADXlRPkLeFS+08f7dGg6RxbG5gug+yQLnw1ARNDYx6zK0gtHU+qmUlBCVqHS5vqAt73ydDKUGY9IgdMcxWtbPj456wF7W86xDv6EfiV/G9ZRVvPWmgNUxw1RXtQa91sIuyCxp4xIFd43wROxWUbmN+Omiv2ZYqYBquSdmzslL1dDypPCZ53ZCs1aY6TodbhndySp8E7YAhw8o+F2uGPW9p1Xz1w4hIZBo10b49rOpR5h0t2U4OloBbAC8Too6Smb5ZdYseUZLLD+PW1O0l7uMBlmJuqjPXRUxuTwXUO+EA4Z/ymBXalE4Zi3uEomISqWajSDPOG4pwIDAQAB";
String jwtToken = "eyJhbGciOiJSUzI1NiJ9.eyJlbXBsb3llZUpvYklkIjoiNjIxMzI1MDMwNzAwMDAwMDAwMSIsIm1hbmFnZVVuaXRJZCI6IjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDExNjIwNTAxIiwib3JpZ2luQXBwIjoiYzQ1Y2I1YzMwZDQzNGMyNDlkZWYyZGNiMzM2ODg4NGQiLCJ0YXJnZXRDbGllbnRzIjoiNmY5MzhkYTBlMjI5MTFmMGJjNzFiYzE2OTUwYTU1ZmIiLCJlbXBsb3llZUlkIjoiMDAwMDAwMDAwMDAwMDAwMDEwNjIwNTAxMDAwMDA0MjIiLCJ1c2VyVHlwZSI6IjAwMDAwMSIsInVzZXJOYW1lIjoi5p2c5YevIiwib3JnVW5pdElkIjoiMDAwMDAwMDAwMDAwMDAwMDAwMDAxMTYyMDUwMTAxMDciLCJnbXRDcmVhdGUiOiIyMDI1LTEyLTI2IDA4OjAxOjA5IiwidXNlcklkIjoiNjIxMzIzMDIyMzAwMDAwMDAzNDAwMDAiLCJhY2NvdW50IjoiRFVLQUkifQ.LzvpEPcGBeOnfV0tcO9yl11PeWuGQR0lzrRAmdUAcSGhvL-J_UF57P4_Q64qfMrzotoSEiVKiCErs4XcgexDFg4WIpx-wbZWdaQ7zIaFMWY-4eVe3R8Th72ABohwuQ7YRFJuWuNE21m3olfqbnbQ1DztDlsWrjd0l6LohrycK9A0teCAlP4Hhjl9kjT2UrRnMFVep1t5dTz8oPSE4KXNjseG8aTBGYbg304JYFQSfkdn3rB6ucp9FG0b9HGrpw1kCdq16m2VXGmKlqGizrOFw30SEZ9z9dABWiNMZjt3AqhY1ByNFtx0bNY-51DOdfVHeWTUDqItuwOak86r-ZVH_w";
try {
Claims claims = verifyJWTToken(jwtToken, publicKeyStr);
String account = claims.get("account", String.class);
System.out.println("验证成功!");
System.out.println("account: " + account);
System.out.println("过期时间: " + claims.getExpiration());
} catch (Exception e) {
System.err.println("验证失败: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,80 @@
package com.tobacco.mp.utils;
import com.alibaba.fastjson.JSON;
import java.util.*;
public class Maps {
/**
* json去除key-value处理
* @param json
* @return
*/
public static String jsonRemoveKey(String json, String key) {
Map map = JSON.parseObject(json);
Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Object> entry = iter.next();
if (entry.getKey() != null && entry.getKey().equals(key)) {
map.remove(key);
break;
}
}
return JSON.toJSONString(map);
}
/**
* 默认采用HashMap
* @param args
* @return
*/
public static Map<Object,Object> map(Object ... args){
Map<Object,Object> map = new HashMap<Object, Object>();
fillMap(map, args);
return map;
}
/**
* 默认采用HashMap
* @param args
* @return
*/
public static <K,V> Map<K,V> map(Class<K> kClazz,Class<V> vClassz,Object ... args){
Map<K,V> map = new HashMap<K, V>();
if (args.length % 2 == 0){
for (int i = 0;i < args.length; i+=2){
map.put((K)args[i], (V)args[i+1]);
}
}
return map;
}
public static Map<Object,Object> treemap(Object ... args){
Map<Object,Object> map = new TreeMap<Object, Object>();
fillMap(map, args);
return map;
}
public static <T,V> Map<T,V> copy(Map<T,V> source){
if (source == null){
return Collections.emptyMap();
}
if (source instanceof LinkedHashMap){
return new LinkedHashMap<T,V>(source);
} else if (source instanceof TreeMap){
return new TreeMap<T,V>(source);
} else {
return new HashMap<T,V>(source);
}
}
private static void fillMap(Map target,Object ... args){
if (args.length % 2 == 0){
for (int i = 0;i < args.length; i+=2){
target.put(args[i], args[i+1]);
}
}
}
}

View File

@ -0,0 +1,249 @@
package com.tobacco.mp.utils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
*
*/
public final class Objects {
public static <T> List<T> take(List list, String name, Class<T> clazz) {
try {
List<T> values = new ArrayList<>();
for (Object item : list) {
Object valueObj = PropertyUtils.getProperty(item, name);
T value = (T) valueObj;
if (value != null) {
values.add(value);
}
}
return values;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
public static <I, T> Map<I, T> index(List<T> list, String name, Class<I> clazz) {
try {
Map<I, T> index = new HashMap<>();
for (T t : list) {
Object valueObj = PropertyUtils.getProperty(t, name);
I key = (I) valueObj;
index.put(key, t);
}
return index;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
/**
* @param target
* @param source
* @param mapKey 默认两个对象之间通过mapKey关联即source中对应的是idtarget中对应的对象的属性是mapKey.replace("Id")
*/
public static void orm(List target, List source, String mapKey) {
try {
String defaultID = "id";
Map<Object, Object> index = index(source, defaultID, Object.class);
String name = mapKey.substring(0, mapKey.length() - defaultID.length());
for (Object t : target) {
Object mapValue = PropertyUtils.getProperty(t, mapKey);
Object value = index.get(mapValue);
PropertyUtils.setProperty(t, name, value);
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
public static void orm(List target, List source, String mapKey, String name) {
try {
String defaultID = "id";
Map<Object, Object> index = index(source, defaultID, Object.class);
for (Object t : target) {
Object mapValue = PropertyUtils.getProperty(t, mapKey);
if(mapValue != null) {
Object value = index.get(Long.parseLong(mapValue.toString()));
PropertyUtils.setProperty(t, name, value);
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
public static boolean isEmpty(Object value) {
if (value == null) {
return true;
}
if (value instanceof Integer) {
return value.equals(Integer.valueOf(0));
} else if (value instanceof String) {
return StringUtils.isEmpty(value.toString());
}
return false;
}
public static Map<Object, List> group(List list, String prop) {
try {
Map<Object, List> groupIndex = new HashMap<>();
for (Object item : list) {
Object value = PropertyUtils.getProperty(item, prop);
if (value != null) {
List group = groupIndex.get(value);
if (group == null) {
group = new LinkedList();
groupIndex.put(value, group);
}
group.add(item);
}
}
return groupIndex;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
/**
* list去重
* @param list
* @return
*/
public static List removeDuplicate(List list) {
for ( int i = 0 ; i < list.size() - 1 ; i ++ ) {
for ( int j = list.size() - 1 ; j > i; j -- ) {
if (list.get(j).equals(list.get(i))) {
list.remove(j);
}
}
}
return list;
}
/**
* 检查一个列表对象是否有数据
* @param objs
* @return
*/
public static <T> boolean checkObjFieldIsData(Collection<T> objs, String...keys) {
try {
for (T obj : objs) {
if (checkObjField(obj, keys)) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 检查一个列表对象是否有数据
* @param objs false 表示
* @return
*/
public static <T> boolean checkObjFieldIsData(Map<String, List<T>> objs, String...keys) {
try {
Iterator<Map.Entry<String, List<T>>> iter = objs.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, List<T>> entry = iter.next();
for (Object obj : entry.getValue()) {
if (checkObjField(obj, keys)) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 去掉设备类型没有在线率的统计
* @param map
*/
public static <T> void deleteNullDeviceType(Map<Integer, List<T>> map, String...keys) {
List<Integer> eventTypes = new ArrayList<>();
Iterator<Map.Entry<Integer, List<T>>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<Integer, List<T>> entry = iter.next();
boolean result = checkObjFieldIsData(entry.getValue(), keys);
if (!result) {
eventTypes.add(entry.getKey());
}
}
for (Integer s: eventTypes) {
map.remove(s);
}
}
/**
* 检测对象是否有数据
* @param obj
* @return
* @throws IllegalAccessException
*/
private static boolean checkObjField(Object obj, String...keys) throws IllegalAccessException{
for (Field f : obj.getClass().getDeclaredFields()) {
f.setAccessible(true);
if (keys != null) {
boolean isCheck = true;
for (String key : keys) {
if (key.equals(f.getName())) {
isCheck = false;
break;
}
}
if (!isCheck) {
continue;
}
}
if (obj instanceof String && f.get(obj) != null) {
if (!"".equals(String.valueOf(f.get(obj)))) {
return true;
}
} else if (obj instanceof Number && f.get(obj) != null) {
if (!"0".equals(String.valueOf(f.get(obj)))) {
return true;
}
} else if (f.get(obj) != null) {
if (!"0".equals(String.valueOf(f.get(obj)))) {
return true;
}
}
}
return false;
}
}

View File

@ -0,0 +1,163 @@
package com.tobacco.mp.utils;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.MessageDigest;
import java.security.SecureRandom;
/**
* 加密加盐工具
*/
public class PasswordUtil {
public static final String ALGORITHM = "PBEWITHMD5andDES";
public static final int ITERATION_COUNT = 100;
public static final String PRIVATE_KRY = "MD5";
public static byte[] initSalt() throws Exception {
// 实例化安全随机数
SecureRandom random = new SecureRandom();
return random.generateSeed(8);
}
/**
* md5加密处理
* @param s
* @return
*/
private static String md5(String s) {
try {
// MessageDigest是封装md5算法的工具对象还支持SHA算法
MessageDigest md = MessageDigest.getInstance("MD5");
// 通过digest拿到的任意字符串,得到的bates都是等长的
byte[] bytes = md.digest(s.getBytes(StandardCharsets.UTF_8));
return toHex(bytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 二进制转十六进制
* @param bytes 二进制数据
* @return
*/
private static String toHex(byte[] bytes) {
// 把二进制转换成十六进制字符串
char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
StringBuilder ret = new StringBuilder(bytes.length * 2);
// 循环判断是为了补位操作
for (int i = 0; i < bytes.length; i++) {
ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
}
return ret.toString();
}
/**
* 对密码进行加密加盐操作
* @param password
* @return
*/
public static String encode(String password, String salt) {
//加密
String hexPwd = md5(password);
//加盐操作
StringBuilder builder = new StringBuilder(hexPwd);
builder.insert(18, salt);
//返回加密加盐后的字符串
return builder.toString();
}
/**
* 校对密码是否匹配匹配则返回true
* @param password
* @param dbPassword
* @return
*/
public static boolean match(String password, String dbPassword) {
StringBuilder builder = new StringBuilder(dbPassword);
//去盐操作生成md5加密后原始字符
builder.replace(18, 26, "");
//加密新密码生成md5加密字符
password = md5(password);
//校对加密字符与原始字符是否匹配
return password.equals(builder.toString());
}
/***
* 转换密钥函数
* @param password 密码
* @return 密钥
*/
private static Key toKey(String password) throws Exception {
//密钥材料
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
//实例化
SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
//生成密钥
return factory.generateSecret(keySpec);
}
/***
* @Deprecated 加密函数
* @param data 待加密数据
*/
public static String newEncrypt(String data, String salt) throws Exception {
// 盐加密转换为数组类型
byte[] saltByte = salt.getBytes();
// 通过私钥拿到密钥
Key key = toKey(PRIVATE_KRY);
// 创建算法实体类
PBEParameterSpec spec = new PBEParameterSpec(saltByte, ITERATION_COUNT);
// 创建加密实体类
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 通过私钥和算法类初始化加密构造
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
// 方法需要数组 这里直接封装好了
return DatatypeConverter.printBase64Binary(cipher.doFinal(data.getBytes()));
}
/***
* @Deprecated 解密函数
* @param encrypt 待解密数据
*/
public static String newDecrypt(String encrypt, String salt) {
try {
// 盐加密转换为数组类型
byte[] saltByte = salt.getBytes();
// 通过私钥拿到密钥
Key key = toKey(PRIVATE_KRY);
// 创建算法实体类
PBEParameterSpec spec = new PBEParameterSpec(saltByte, ITERATION_COUNT);
// 创建加密实体类
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 通过私钥和算法类初始化加密构造
cipher.init(Cipher.DECRYPT_MODE, key, spec);
// 方法需要数组 这里直接封装好了
byte[] decode = DatatypeConverter.parseBase64Binary(encrypt);
return new String(cipher.doFinal(decode));
} catch (Exception e) {
e.printStackTrace();
return salt;
}
}
public static void main(String[] args) throws Exception {
// String salt = RandomUtil.generateString(8);
// String salt = "UhHoJ6Z8";
// String password = "123456";
// System.err.println("盐值:" + salt);
// System.err.println("密码:" + newEncrypt(password, salt));
// System.err.println(newDecrypt("qYc/bjJN5cI+bQjFQaEoMA==","WZIpOlpa"));
System.err.println(newDecrypt("fihwsY8n4KDkh0wCaKrZpQ==", "sUio5KqE"));
}
}

View File

@ -0,0 +1,95 @@
package com.tobacco.mp.utils;
import java.util.Random;
/**
* 随机数工具
*/
public class RandomUtil {
public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String LETTERCHAR = "abcdefghijkllmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* 返回一个定长的随机字符串(只包含大小写字母、数字)
* @param length 随机字符串长度
* @return 随机字符串
*/
public static String generateString(int length) {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
}
return sb.toString();
}
/**
* 返回一个定长的随机纯字母字符串(只包含大小写字母)
* @param length 随机字符串长度
* @return 随机字符串
*/
public static String generateMixString(int length) {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(ALLCHAR.charAt(random.nextInt(LETTERCHAR.length())));
}
return sb.toString();
}
/**
* 返回一个定长的随机纯大写字母字符串(只包含大小写字母)
* @param length 随机字符串长度
* @return 随机字符串
*/
public static String generateLowerString(int length) {
return generateMixString(length).toLowerCase();
}
/**
* 返回一个定长的随机纯小写字母字符串(只包含大小写字母)
* @param length 随机字符串长度
* @return 随机字符串
*/
public static String generateUpperString(int length) {
return generateMixString(length).toUpperCase();
}
/**
* 生成一个定长的纯0字符串
* @param length 字符串长度
* @return 纯0字符串
*/
public static String generateZeroString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append('0');
}
return sb.toString();
}
/**
* 根据数字生成一个定长的字符串长度不够前面补0
* @param num 数字
* @param fixdLenth 字符串长度
* @return 定长的字符串
*/
public static String toFixdLengthString(long num, int fixdLenth) {
StringBuilder sb = new StringBuilder();
String strNum = String.valueOf(num);
if (fixdLenth - strNum.length() >= 0) {
sb.append(generateZeroString(fixdLenth - strNum.length()));
} else {
throw new RuntimeException("将数字" + num + "转化为长度为" + fixdLenth + "的字符串发生异常!");
}
sb.append(strNum);
return sb.toString();
}
public static void main(String[] args) {
System.out.println("定长的随机字符串(只包含大小写字母、数字):" + generateString(10));
}
}

View File

@ -0,0 +1,317 @@
package com.tobacco.mp.utils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* Redis工具
*/
@Component(value = "redisUtils")
public class RedisUtils {
@Resource
private RedisTemplate<String, Object> redisTemplate;
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 设置过期时间
* @param key
* @param expireTime
* @param unit
*/
public void setExpire(String key, Long expireTime, TimeUnit unit) {
redisTemplate.expire(key, expireTime, unit);
}
/**
* 递增
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
/**
* 获取redis中缓存信息
* @return
*/
public List<String> getRedisCacheMessage() {
List<String> list = new ArrayList<>();
Set<String> keys = redisTemplate.keys("*");
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext()) {
list.add(iterator.next());
}
return list;
}
}

44
cdaxxt-core/pom.xml Normal file
View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>integration-platform-access</artifactId>
<groupId>com.tobacco.mp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cdaxxt-core</artifactId>
<dependencies>
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>cdaxxt-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
</build>
</project>

282
pom.xml Normal file
View File

@ -0,0 +1,282 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tobacco.mp</groupId>
<artifactId>integration-platform-access</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>cdaxxt-bootstrap</module>
<module>cdaxxt-business</module>
<module>cdaxxt-common</module>
<module>cdaxxt-core</module>
<module>assembly</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
<exclusions>
<exclusion>
<artifactId>tomcat-jdbc</artifactId>
<groupId>org.apache.tomcat</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.13</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.16</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>11.8</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<!--业务中台对接SDK-->
<!--阿里云网关-->
<dependency>
<groupId>com.aliyun.bizworks</groupId>
<artifactId>ubcp-api-client</artifactId>
<version>1.13.0-SNAPSHOT</version>
</dependency>
<!--用户中心-->
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>tobacco-mp-uc-client</artifactId>
<version>2.6.8-RELEASE</version>
</dependency>
<!--核心包-->
<dependency>
<groupId>com.alibaba.bizworks</groupId>
<artifactId>core-common</artifactId>
<version>1.17.1</version>
</dependency>
<!--用户认证包-->
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>tobacco-mp-auth-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<!--消息中心包-->
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>tobacco-mp-mcext-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<!--待办中心-->
<dependency>
<groupId>com.tobacco.mp</groupId>
<artifactId>tobacco-mp-ttc-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
<!-- <repositories>
<repository>
<id>aliyun</id>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</repository>
<repository>
<id>google</id>
<url>http://maven.aliyun.com/nexus/content/repositories/google</url>
</repository>
<repository>
<id>jcenter</id>
<url>http://maven.aliyun.com/nexus/content/repositories/jcenter</url>
</repository>
<repository>
<id>bizworks-repo</id>
<url>http://bizworks-nexus.console.gansu.zgs.yun/repositories/ywzt-public</url>
</repository>
<repository>
<id>bizworks-repo</id>
<url>http://bizworks-nexus.console.gansu.zgs.yun/repository/yth-portal</url>
</repository>
</repositories>-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
<useIncrementalCompilation>false</useIncrementalCompilation>
</configuration>
</plugin>
</plugins>
</build>
</project>