Compare commits
No commits in common. "d23527adbef3feedf409fedd7e13f1cc548c7f4b" and "ad0de6a29aed68740d3254b08919f1de6505c357" have entirely different histories.
d23527adbe
...
ad0de6a29a
README.mdcell_db_tcp-20210402.sqlcell_db_tcp-20210406.sqlcell_db_v1.0.sql
libs
pom.xmlshapelight-admin
Dockerfilepom.xml
src/main/java/net/shapelight
AdminApplication.java
common
annotation
aspect
base
config
CorsConfig.javaFilterConfig.javaFreemarkerConfig.javaGlobalValue.javaKaptchaConfig.javaMinioConfig.javaMinioUtils.javaMybatisPlusConfig.javaRestTemplateConfig.javaShiroConfig.javaSwaggerConfig.javaTomcatConfig.javaWebConfig.javaWxMappingJackson2HttpMessageConverter.java
shard
sharding
shardingdangdang
exception
handler
swaggermap
utils
BeanUtils.javaCollectionUtils.javaCompressZipUtils.javaConfigConstant.javaConstant.javaConvert.javaExcelUtils.javaFileUploadUtils.javaHttpConnectionUtils.javaHttpContextUtils.javaHttpsClientRequestFactory.javaITree.javaImageUtil.javaImageUtils.javaIpUtils.javaMD5Utils.javaMimeTypeUtils.javaMinIOTest.javaMinioUtil.javaMyBeanUtils.javaMyDateUtils.javaPrivacyUtil.javaQuery.javaRedisKeys.javaRestTemplateUtils.javaServletUtils.javaSnowflakeIdWorker.javaStringUtils.javaThumbnailsUtils.javaTreeUtils.javaUUIDUtil.javaUploadZipUtil.javaZipExample.java
validator/group
modules/app
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
@ -0,0 +1,340 @@
|
|||
<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>shapelight.net</groupId>
|
||||
<artifactId>shapelight-cell</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<name>shapelight-cell</name>
|
||||
<url>https://www.shapelight.net</url>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.7.RELEASE</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>shapelight-common</module>
|
||||
<module>shapelight-admin</module>
|
||||
<!--<module>shapelight-api</module>-->
|
||||
<!--<module>shapelight-dynamic-datasource</module>-->
|
||||
<module>shapelight-engine</module>
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<jedis.version>2.9.0</jedis.version>
|
||||
<druid.version>1.2.13</druid.version>
|
||||
<mybatisplus.version>3.5.7</mybatisplus.version>
|
||||
<mysql.version>8.0.25</mysql.version>
|
||||
<mssql.version>4.0</mssql.version>
|
||||
<oracle.version>11.2.0.3</oracle.version>
|
||||
<commons.lang.version>2.6</commons.lang.version>
|
||||
<commons.fileupload.version>1.3.1</commons.fileupload.version>
|
||||
<commons.io.version>2.5</commons.io.version>
|
||||
<commons.codec.version>1.10</commons.codec.version>
|
||||
<fastjson.version>1.2.78</fastjson.version>
|
||||
<joda.time.version>2.9.9</joda.time.version>
|
||||
<lombok.version>1.18.4</lombok.version>
|
||||
<swagger.version>2.7.0</swagger.version>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<!--<sharding.jdbc.version>3.0.0</sharding.jdbc.version>-->
|
||||
<sharding.jdbc.version>2.0.3</sharding.jdbc.version>
|
||||
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<!-- SpringCloud 版本依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>${spring-cloud.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>2.17.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-aop</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context-support</artifactId>
|
||||
</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-validation</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>redis.clients</groupId>
|
||||
<artifactId>jedis</artifactId>
|
||||
<version>${jedis.version}</version>
|
||||
</dependency>
|
||||
<!-- mysql驱动 -->
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>${mysql.version}</version>
|
||||
</dependency>
|
||||
<!-- oracle驱动 -->
|
||||
<dependency>
|
||||
<groupId>com.oracle</groupId>
|
||||
<artifactId>ojdbc6</artifactId>
|
||||
<version>${oracle.version}</version>
|
||||
</dependency>
|
||||
<!-- mssql驱动 -->
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>sqljdbc4</artifactId>
|
||||
<version>${mssql.version}</version>
|
||||
</dependency>
|
||||
<!-- postgresql驱动 -->
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
|
||||
<!--<dependency>-->
|
||||
<!--<groupId>org.apache.shardingsphere</groupId>-->
|
||||
<!--<artifactId>sharding-jdbc-core</artifactId>-->
|
||||
<!--<version>4.0.1</version>-->
|
||||
<!--</dependency>-->
|
||||
<!--<dependency>
|
||||
<groupId>io.shardingsphere</groupId>
|
||||
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
|
||||
<version>${sharding.jdbc.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.shardingsphere</groupId>
|
||||
<artifactId>sharding-jdbc-spring-namespace</artifactId>
|
||||
<version>${sharding.jdbc.version}</version>
|
||||
</dependency>-->
|
||||
|
||||
<!--<dependency>
|
||||
<groupId>io.shardingjdbc</groupId>
|
||||
<artifactId>sharding-jdbc-core</artifactId>
|
||||
<version>2.0.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.shardingjdbc</groupId>
|
||||
<artifactId>sharding-jdbc-core-spring-namespace</artifactId>
|
||||
<version>2.0.3</version>
|
||||
</dependency>-->
|
||||
|
||||
|
||||
|
||||
<!--<dependency>
|
||||
<groupId>io.shardingsphere</groupId>
|
||||
<artifactId>sharding-jdbc-core</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</dependency>-->
|
||||
|
||||
|
||||
<!--<dependency>
|
||||
<groupId>org.apache.shardingsphere</groupId>
|
||||
<artifactId>sharding-jdbc-spring-namespace</artifactId>
|
||||
<version>4.0.0-RC2</version>
|
||||
</dependency>-->
|
||||
|
||||
<!--<dependency>
|
||||
<groupId>com.dangdang</groupId>
|
||||
<artifactId>sharding-jdbc-config-spring</artifactId>
|
||||
<version>1.5.4.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.shardingjdbc</groupId>
|
||||
<artifactId>sharding-jdbc-core</artifactId>
|
||||
<version>2.0.3</version>
|
||||
</dependency>-->
|
||||
|
||||
<dependency>
|
||||
<groupId>io.minio</groupId>
|
||||
<artifactId>minio</artifactId>
|
||||
<version>7.0.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.coobird</groupId>
|
||||
<artifactId>thumbnailator</artifactId>
|
||||
<version>0.4.8</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid-spring-boot-starter</artifactId>
|
||||
<version>${druid.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
<version>${mybatisplus.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-generator</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>${fastjson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-lang</groupId>
|
||||
<artifactId>commons-lang</artifactId>
|
||||
<version>${commons.lang.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-fileupload</groupId>
|
||||
<artifactId>commons-fileupload</artifactId>
|
||||
<version>${commons.fileupload.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons.io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons.codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda.time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
<version>${swagger.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${swagger.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.coobird</groupId>
|
||||
<artifactId>thumbnailator</artifactId>
|
||||
<version>0.4.13</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-ext-jdk16</artifactId>
|
||||
<version>1.45</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.yulichang</groupId>
|
||||
<artifactId>mybatis-plus-join-boot-starter</artifactId>
|
||||
<version>1.5.0</version>
|
||||
</dependency>
|
||||
<!--mapstruct-->
|
||||
<dependency>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct</artifactId>
|
||||
<version>1.6.0.Beta1</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
<!-- 阿里云maven仓库 -->
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>public</id>
|
||||
<name>aliyun nexus</name>
|
||||
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
</releases>
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>public</id>
|
||||
<name>aliyun nexus</name>
|
||||
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
</releases>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
</project>
|
|
@ -0,0 +1,20 @@
|
|||
# 使用官方Java运行环境作为基础镜像
|
||||
FROM openjdk:8
|
||||
|
||||
# 指定维护者信息
|
||||
LABEL maintainer="zhangbo"
|
||||
|
||||
# 在镜像中创建一个目录存放我们的Spring Boot应用
|
||||
VOLUME /tmp
|
||||
|
||||
# 将jar包添加到容器中并更名为app.jar
|
||||
ADD target/shapelight-admin.jar app.jar
|
||||
|
||||
# 暴露容器内的端口给外部访问
|
||||
EXPOSE 8018
|
||||
|
||||
# 定义环境变量
|
||||
ENV JAVA_OPTS="-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8095"
|
||||
|
||||
# 在容器启动时运行jar包
|
||||
ENTRYPOINT exec java $JAVA_OPTS -Djava.security.egd=file:/dev/./cell -jar /app.jar
|
|
@ -0,0 +1,369 @@
|
|||
<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>
|
||||
<groupId>shapelight.net</groupId>
|
||||
<artifactId>shapelight-cell</artifactId>
|
||||
<version>2.0.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>shapelight-admin</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<description>shapelight-admin</description>
|
||||
|
||||
<properties>
|
||||
<quartz.version>2.3.0</quartz.version>
|
||||
<shiro.version>1.10.0</shiro.version>
|
||||
<jwt.version>0.7.0</jwt.version>
|
||||
<kaptcha.version>0.0.9</kaptcha.version>
|
||||
<!--<qiniu.version>[7.2.0, 7.2.99]</qiniu.version>-->
|
||||
<!--<aliyun.oss.version>2.5.0</aliyun.oss.version>-->
|
||||
<!--<qcloud.cos.version>4.4</qcloud.cos.version>-->
|
||||
<swagger.version>2.7.0</swagger.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>shapelight.net</groupId>
|
||||
<artifactId>shapelight-common</artifactId>
|
||||
<version>2.0.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>redis.clients</groupId>-->
|
||||
<!-- <artifactId>jedis</artifactId>-->
|
||||
<!-- <version>2.9.0</version>-->
|
||||
<!-- </dependency>-->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.springframework.data</groupId>-->
|
||||
<!-- <artifactId>spring-data-redis</artifactId>-->
|
||||
<!-- <version>2.1.10.RELEASE</version>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-pool2</artifactId>
|
||||
<version>2.6.2</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 集群环境,需要打开注释 -->
|
||||
<!--<dependency>-->
|
||||
<!--<groupId>org.springframework.session</groupId>-->
|
||||
<!--<artifactId>spring-session-data-redis</artifactId>-->
|
||||
<!--</dependency>-->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-freemarker</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.quartz-scheduler</groupId>
|
||||
<artifactId>quartz</artifactId>
|
||||
<version>${quartz.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.mchange</groupId>
|
||||
<artifactId>c3p0</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>com.zaxxer</groupId>
|
||||
<artifactId>HikariCP-java6</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.shiro</groupId>
|
||||
<artifactId>shiro-core</artifactId>
|
||||
<version>${shiro.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.shiro</groupId>
|
||||
<artifactId>shiro-spring</artifactId>
|
||||
<version>${shiro.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.shiro</groupId>
|
||||
<artifactId>shiro-ehcache</artifactId>
|
||||
<version>${shiro.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.axet</groupId>
|
||||
<artifactId>kaptcha</artifactId>
|
||||
<version>${kaptcha.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger2</artifactId>
|
||||
<version>${swagger.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${swagger.version}</version>
|
||||
</dependency>
|
||||
<!--<dependency>-->
|
||||
<!--<groupId>com.qiniu</groupId>-->
|
||||
<!--<artifactId>qiniu-java-sdk</artifactId>-->
|
||||
<!--<version>${qiniu.version}</version>-->
|
||||
<!--</dependency>-->
|
||||
<!--<dependency>-->
|
||||
<!--<groupId>com.aliyun.oss</groupId>-->
|
||||
<!--<artifactId>aliyun-sdk-oss</artifactId>-->
|
||||
<!--<version>${aliyun.oss.version}</version>-->
|
||||
<!--</dependency>-->
|
||||
<!--<dependency>-->
|
||||
<!--<groupId>com.qcloud</groupId>-->
|
||||
<!--<artifactId>cos_api</artifactId>-->
|
||||
<!--<version>${qcloud.cos.version}</version>-->
|
||||
<!--<exclusions>-->
|
||||
<!--<exclusion>-->
|
||||
<!--<groupId>org.slf4j</groupId>-->
|
||||
<!--<artifactId>slf4j-log4j12</artifactId>-->
|
||||
<!--</exclusion>-->
|
||||
<!--</exclusions>-->
|
||||
<!--</dependency>-->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.8.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.codehaus.jackson</groupId>
|
||||
<artifactId>jackson-mapper-asl</artifactId>
|
||||
<version>1.9.13</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 导入zip解压包 -->
|
||||
<dependency>
|
||||
<groupId>ant</groupId>
|
||||
<artifactId>ant</artifactId>
|
||||
<version>1.6.5</version>
|
||||
</dependency>
|
||||
<!-- 导入rar解压包 -->
|
||||
<dependency>
|
||||
<groupId>com.github.junrar</groupId>
|
||||
<artifactId>junrar</artifactId>
|
||||
<version>0.7</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.guwan</groupId>
|
||||
<artifactId>easyexcel</artifactId>
|
||||
<version>4.0.3</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>easyexcel</artifactId>
|
||||
<version>1.1.2-beta5</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>io.github.swagger2markup</groupId>
|
||||
<artifactId>swagger2markup</artifactId>
|
||||
<version>1.3.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.netzwerg</groupId>
|
||||
<artifactId>paleo-core</artifactId>
|
||||
<version>0.10.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>0.9.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>net.java.dev.jna</groupId>
|
||||
<artifactId>jna</artifactId>
|
||||
<version>5.4.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt</artifactId>
|
||||
<version>${jwt.version}</version>
|
||||
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-all</artifactId>
|
||||
<version>5.7.16</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-integration</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.integration</groupId>
|
||||
<artifactId>spring-integration-stream</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.integration</groupId>
|
||||
<artifactId>spring-integration-mqtt</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
|
||||
<!--<dependency>
|
||||
<groupId>shapelight.net</groupId>
|
||||
<artifactId>shapelight-dynamic-datasource</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<!–<scope>test</scope>–>
|
||||
</dependency>-->
|
||||
<dependency>
|
||||
<groupId>shapelight.net</groupId>
|
||||
<artifactId>shapelight-engine</artifactId>
|
||||
<version>2.0.0</version>
|
||||
<!--<scope>test</scope>-->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.arcsoft.face</groupId>
|
||||
<artifactId>arcsoft-sdk-face</artifactId>
|
||||
<version>4.1.1.0</version>
|
||||
<!-- <scope>system</scope>-->
|
||||
<!-- <systemPath>${project.basedir}/libs/arcsoft-sdk-face-3.0.0.0.jar</systemPath>-->
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<!-- 跳过单元测试 -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<skipTests>true</skipTests>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!-- <plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>-->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.11.0</version>
|
||||
<configuration>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.34</version>
|
||||
</path>
|
||||
<path>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct-processor</artifactId>
|
||||
<version>1.6.0.Beta1</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
|
||||
<!-- docker的maven插件官网:https://github.com/spotify/docker-maven-plugin -->
|
||||
<plugin>
|
||||
<groupId>com.spotify</groupId>
|
||||
<artifactId>docker-maven-plugin</artifactId>
|
||||
<version>1.2.2</version>
|
||||
<configuration>
|
||||
<!--配置最终生成的镜像名称-->
|
||||
<imageName>shapelight/admin</imageName>
|
||||
<baseImage>java:8-alpine</baseImage>
|
||||
<entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
|
||||
<resources>
|
||||
<resource>
|
||||
<targetPath>/</targetPath>
|
||||
<directory>${project.build.directory}</directory>
|
||||
<include>${project.build.finalName}.jar</include>
|
||||
</resource>
|
||||
</resources>
|
||||
<!--配置 docker 的地址,当运行 docker build 命令时构建并上传镜像-->
|
||||
<dockerHost>http://192.168.10.62:2375</dockerHost>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!--<plugin>
|
||||
<groupId>com.spotify</groupId>
|
||||
<artifactId>docker-maven-plugin</artifactId>
|
||||
<version>0.4.14</version>
|
||||
<configuration>
|
||||
<imageName>shapelight/admin</imageName>
|
||||
<dockerDirectory>${project.basedir}</dockerDirectory>
|
||||
<dockerHost>http://192.168.10.62:2375</dockerHost>
|
||||
<resources>
|
||||
<resource>
|
||||
<targetPath>/</targetPath>
|
||||
<directory>${project.build.directory}</directory>
|
||||
<include>${project.build.finalName}.jar</include>
|
||||
</resource>
|
||||
</resources>
|
||||
</configuration>
|
||||
<!– 运行命令 mvn clean package docker:build 打包并生成docker镜像 –>
|
||||
</plugin>-->
|
||||
<!--<plugin>
|
||||
<groupId>com.spotify</groupId>
|
||||
<artifactId>docker-maven-plugin</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<configuration>
|
||||
<!– 镜像名称 guoweixin/exam–>
|
||||
<imageName>${project.artifactId}</imageName>
|
||||
<!–指定标签–>
|
||||
<imageTags>
|
||||
<imageTag>latest</imageTag>
|
||||
</imageTags>
|
||||
<!– 基础镜像jdk 1.8–>
|
||||
<baseImage>java</baseImage>
|
||||
<!– 制作者提供本人信息 –>
|
||||
<maintainer>zdk=20477@sina.com</maintainer>
|
||||
<runs>
|
||||
<run>mkdir -p /opt/java/</run>
|
||||
</runs>
|
||||
<!–切换到/ROOT目录 –>
|
||||
<workdir>/ROOT</workdir>
|
||||
<cmd>["java", "-version"]</cmd>
|
||||
<entryPoint>["java", "-jar", "${project.build.finalName}.jar"]</entryPoint>
|
||||
<!– 指定 Dockerfile 路径
|
||||
<dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
|
||||
–>
|
||||
<!–指定远程 docker api地址–>
|
||||
<dockerHost>http://192.168.10.62:2375</dockerHost>
|
||||
<!– 这里是复制 jar 包到 docker 容器指定目录配置 –>
|
||||
<resources>
|
||||
<resource>
|
||||
<targetPath>/ROOT</targetPath>
|
||||
<!–用于指定需要复制的根目录,${project.build.directory}表示target目录–>
|
||||
<directory>${project.build.directory}</directory>
|
||||
<!–用于指定需要复制的文件。${project.build.finalName}.jar指的是打包后的jar
|
||||
包文件。–>
|
||||
<include>${project.build.finalName}.jar</include>
|
||||
</resource>
|
||||
</resources>
|
||||
</configuration>
|
||||
</plugin>-->
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,50 @@
|
|||
/**/
|
||||
|
||||
package net.shapelight;
|
||||
|
||||
//import net.shapelight.modules.dev.mqtt.MqttClientUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
/*import net.shapelight.commons.engine.sdk.PalmSDK;
|
||||
import org.mybatis.spring.annotation.MapperScan;*/
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||
import org.springframework.boot.web.servlet.ServletComponentScan;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||
import org.springframework.context.annotation.ImportResource;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
@Slf4j
|
||||
//@ImportResource(value = { "classpath:spring/spring.xml" })
|
||||
@SpringBootApplication//(exclude = DataSourceAutoConfiguration.class)//排除DataSourceConfiguratrion
|
||||
@EnableCaching
|
||||
@EnableTransactionManagement
|
||||
@ServletComponentScan
|
||||
@EnableFeignClients
|
||||
//@MapperScan("net.shapelight.modules.sys.dao")
|
||||
public class AdminApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(AdminApplication.class, args);
|
||||
|
||||
//初始化掌静脉sdk
|
||||
//int initCode = PalmSDK.init();
|
||||
//log.debug("掌静脉sdk初始化。。。。。。。。。。:"+initCode);
|
||||
// //mqtt服务启动
|
||||
// MqttClientUtil.createClient();
|
||||
//
|
||||
Runtime.getRuntime().addShutdownHook(new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
//int code = PalmSDK.release();
|
||||
//log.debug("掌静脉sdk释放。。。。。。。。。。:"+code);
|
||||
} catch (Throwable e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
|
||||
|
||||
package net.shapelight.common.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 数据过滤
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface AreaFilter {
|
||||
/** 表的别名 */
|
||||
String tableAlias() default "";
|
||||
|
||||
/** true:没有本部门数据权限,也能查询本人数据 */
|
||||
boolean user() default true;
|
||||
|
||||
/** true:拥有子部门数据权限 */
|
||||
boolean subArea() default true;
|
||||
|
||||
/** 区域ID */
|
||||
String areaId() default "area_id";
|
||||
|
||||
/** 用户ID */
|
||||
//String userId() default "user_id";
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
|
||||
|
||||
package net.shapelight.common.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 数据过滤
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface DataFilter {
|
||||
/** 表的别名 */
|
||||
String tableAlias() default "";
|
||||
|
||||
/** true:没有本部门数据权限,也能查询本人数据 */
|
||||
boolean user() default true;
|
||||
|
||||
/** true:拥有子部门数据权限 */
|
||||
boolean subDept() default false;
|
||||
|
||||
/** 部门ID */
|
||||
String deptId() default "dept_id";
|
||||
|
||||
/** 用户ID */
|
||||
String userId() default "user_id";
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
|
||||
|
||||
package net.shapelight.common.annotation;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 系统日志注解
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface SysLog {
|
||||
|
||||
String value() default "";
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
|
||||
|
||||
package net.shapelight.common.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 系统日志注解
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface TenLog {
|
||||
|
||||
String value() default "";
|
||||
}
|
|
@ -0,0 +1,140 @@
|
|||
package net.shapelight.common.aspect;
|
||||
|
||||
import net.shapelight.common.annotation.AreaFilter;
|
||||
import net.shapelight.common.exception.RRException;
|
||||
import net.shapelight.common.utils.Constant;
|
||||
import net.shapelight.modules.sys.entity.SysUserEntity;
|
||||
import net.shapelight.modules.sys.shiro.ShiroUtils;
|
||||
import net.shapelight.modules.ten.service.TenAreaService;
|
||||
import net.shapelight.modules.ten.service.TenUserScopeService;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 数据过滤,切面处理类
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class AreaFilterAspect {
|
||||
@Autowired
|
||||
private TenAreaService tenAreaServer;
|
||||
@Autowired
|
||||
private TenUserScopeService tenUserScopeService;
|
||||
|
||||
|
||||
@Pointcut("@annotation(net.shapelight.common.annotation.AreaFilter)")
|
||||
public void areaFilterCut() {
|
||||
|
||||
}
|
||||
|
||||
@Before("areaFilterCut()")
|
||||
public void areaFilter(JoinPoint point) throws Throwable {
|
||||
Object params = point.getArgs()[0];
|
||||
if(params != null && params instanceof Map){
|
||||
SysUserEntity user = ShiroUtils.getUserEntity();
|
||||
|
||||
//如果不是超级管理员,则进行数据过滤
|
||||
/*if(user.getUserId() != Constant.SUPER_ADMIN){
|
||||
Map map = (Map)params;
|
||||
map.put(Constant.SQL_FILTER, getSQLFilter(user, point));
|
||||
}*/
|
||||
int userType = user.getUserType();
|
||||
// if (userType == Constant.SYSTEM_ADMIN) {
|
||||
//
|
||||
// }else if(userType == Constant.SYSTEM_USER){
|
||||
// Map map = (Map)params;
|
||||
// map.put(Constant.SQL_FILTER, getSQLFilter(user, point));
|
||||
// }else if(userType == Constant.TENANT_ADMIN){
|
||||
//
|
||||
// }
|
||||
// else
|
||||
if(userType == Constant.TENANT_USER){
|
||||
Map map = (Map)params;
|
||||
map.put(Constant.SQL_FILTER, getSQLFilter(user, point));
|
||||
}
|
||||
return ;
|
||||
}
|
||||
throw new RRException("数据权限接口,只能是Map类型参数,且不能为NULL");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据过滤的SQL
|
||||
*/
|
||||
private String getSQLFilter(SysUserEntity user, JoinPoint point){
|
||||
MethodSignature signature = (MethodSignature) point.getSignature();
|
||||
AreaFilter areaFilter = signature.getMethod().getAnnotation(AreaFilter.class);
|
||||
//获取表的别名
|
||||
String tableAlias = areaFilter.tableAlias();
|
||||
if(StringUtils.isNotBlank(tableAlias)){
|
||||
tableAlias += ".";
|
||||
}
|
||||
|
||||
//区域ID列表
|
||||
Set<Long> areaIdList = new HashSet<Long>();
|
||||
|
||||
//用户角色对应的部门ID列表
|
||||
// List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
|
||||
// if(roleIdList.size() > 0){
|
||||
// List<Long> userDeptIdList = sysRoleDeptService.queryDeptIdList(roleIdList.toArray(new Long[roleIdList.size()]));
|
||||
// deptIdList.addAll(userDeptIdList);
|
||||
// }
|
||||
|
||||
//当前区域
|
||||
//areaIdList.add(user.getAreaId());
|
||||
//获取用户数据权限对应的areaids
|
||||
List<Long> areaIds = tenUserScopeService.getUserArea(user.getUserId());
|
||||
|
||||
|
||||
//用户子区域ID列表
|
||||
// if(areaFilter.subArea()){
|
||||
// List<Long> subAreaIdList = tenAreaServer.getSubAreaIdList(user.getAreaId());
|
||||
// areaIdList.addAll(subAreaIdList);
|
||||
// }
|
||||
if(areaFilter.subArea()){
|
||||
for(Long areaId: areaIds){
|
||||
//添加自己的区域id
|
||||
areaIdList.add(areaId);
|
||||
List<Long> subAreaIdList = tenAreaServer.getSubAreaIdList(areaId);
|
||||
//添加子区域id
|
||||
areaIdList.addAll(subAreaIdList);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
StringBuilder sqlFilter = new StringBuilder();
|
||||
sqlFilter.append(" (");
|
||||
|
||||
if(areaIdList.size() > 0){
|
||||
sqlFilter.append(tableAlias).append(areaFilter.areaId()).append(" in(").append(StringUtils.join(areaIdList, ",")).append(")");
|
||||
}
|
||||
|
||||
//没有本部门数据权限,也能查询本人数据
|
||||
// if(areaFilter.user()){
|
||||
// if(areaIdList.size() > 0){
|
||||
// sqlFilter.append(" or ");
|
||||
// }
|
||||
// sqlFilter.append(tableAlias).append(areaFilter.userId()).append("=").append(user.getUserId());
|
||||
// }
|
||||
|
||||
sqlFilter.append(")");
|
||||
|
||||
if(sqlFilter.toString().trim().equals("()")){
|
||||
return null;
|
||||
}
|
||||
|
||||
return sqlFilter.toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,196 @@
|
|||
|
||||
|
||||
package net.shapelight.common.aspect;
|
||||
|
||||
|
||||
import net.shapelight.common.annotation.DataFilter;
|
||||
import net.shapelight.common.exception.RRException;
|
||||
import net.shapelight.common.utils.Constant;
|
||||
import net.shapelight.modules.sys.entity.SysUserEntity;
|
||||
import net.shapelight.modules.sys.service.SysDeptService;
|
||||
import net.shapelight.modules.sys.service.SysRoleDeptService;
|
||||
import net.shapelight.modules.sys.service.SysUserRoleService;
|
||||
import net.shapelight.modules.sys.shiro.ShiroUtils;
|
||||
import net.shapelight.common.annotation.DataFilter;
|
||||
import net.shapelight.common.utils.Constant;
|
||||
import net.shapelight.modules.sys.entity.SysUserEntity;
|
||||
import net.shapelight.modules.sys.shiro.ShiroUtils;
|
||||
import oracle.jdbc.driver.Const;
|
||||
import org.apache.commons.beanutils.BeanUtils;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 数据过滤,切面处理类
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class DataFilterAspect {
|
||||
@Autowired
|
||||
private SysDeptService sysDeptService;
|
||||
@Autowired
|
||||
private SysUserRoleService sysUserRoleService;
|
||||
@Autowired
|
||||
private SysRoleDeptService sysRoleDeptService;
|
||||
|
||||
@Pointcut("@annotation(net.shapelight.common.annotation.DataFilter)")
|
||||
public void dataFilterCut() {
|
||||
|
||||
}
|
||||
|
||||
@Before("dataFilterCut()")
|
||||
public void dataFilter(JoinPoint point) throws Throwable {
|
||||
Object params = point.getArgs()[0];
|
||||
if(params != null && params instanceof Map){
|
||||
SysUserEntity user = ShiroUtils.getUserEntity();
|
||||
|
||||
//如果不是超级管理员,则进行数据过滤
|
||||
/*if(user.getUserId() != Constant.SUPER_ADMIN){
|
||||
Map map = (Map)params;
|
||||
map.put(Constant.SQL_FILTER, getSQLFilter(user, point));
|
||||
}*/
|
||||
|
||||
int userType = user.getUserType();
|
||||
|
||||
if (userType == Constant.SYSTEM_ADMIN) {
|
||||
}else if(userType == Constant.SYSTEM_USER){
|
||||
Map map = (Map)params;
|
||||
map.put(Constant.SQL_FILTER, getSQLFilter(user, point));
|
||||
}else if(userType == Constant.TENANT_ADMIN){
|
||||
|
||||
}
|
||||
// else if(userType == Constant.TENANT_USER){
|
||||
// Map map = (Map)params;
|
||||
// TenUserEntity userTen = new TenUserEntity();
|
||||
// try{
|
||||
// BeanUtils.copyProperties(userTen,user);
|
||||
// }catch (Exception e){
|
||||
//
|
||||
// }
|
||||
// map.put(Constant.SQL_FILTER, getSQLFilterTen(userTen, point));
|
||||
// }
|
||||
|
||||
return ;
|
||||
}
|
||||
|
||||
throw new RRException("数据权限接口,只能是Map类型参数,且不能为NULL");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据过滤的SQL
|
||||
*/
|
||||
private String getSQLFilter(SysUserEntity user, JoinPoint point){
|
||||
MethodSignature signature = (MethodSignature) point.getSignature();
|
||||
DataFilter dataFilter = signature.getMethod().getAnnotation(DataFilter.class);
|
||||
//获取表的别名
|
||||
String tableAlias = dataFilter.tableAlias();
|
||||
if(StringUtils.isNotBlank(tableAlias)){
|
||||
tableAlias += ".";
|
||||
}
|
||||
|
||||
//部门ID列表
|
||||
Set<Long> deptIdList = new HashSet<>();
|
||||
|
||||
//用户角色对应的部门ID列表
|
||||
List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
|
||||
if(roleIdList.size() > 0){
|
||||
List<Long> userDeptIdList = sysRoleDeptService.queryDeptIdList(roleIdList.toArray(new Long[roleIdList.size()]));
|
||||
deptIdList.addAll(userDeptIdList);
|
||||
}
|
||||
|
||||
//当前部门
|
||||
deptIdList.add(user.getDeptId());
|
||||
|
||||
//用户子部门ID列表
|
||||
if(dataFilter.subDept()){
|
||||
List<Long> subDeptIdList = sysDeptService.getSubDeptIdList(user.getDeptId());
|
||||
deptIdList.addAll(subDeptIdList);
|
||||
}
|
||||
|
||||
StringBuilder sqlFilter = new StringBuilder();
|
||||
sqlFilter.append(" (");
|
||||
|
||||
if(deptIdList.size() > 0){
|
||||
sqlFilter.append(tableAlias).append(dataFilter.deptId()).append(" in(").append(StringUtils.join(deptIdList, ",")).append(")");
|
||||
}
|
||||
|
||||
//没有本部门数据权限,也能查询本人数据
|
||||
if(dataFilter.user()){
|
||||
if(deptIdList.size() > 0){
|
||||
sqlFilter.append(" or ");
|
||||
}
|
||||
sqlFilter.append(tableAlias).append(dataFilter.userId()).append("=").append(user.getUserId());
|
||||
}
|
||||
|
||||
sqlFilter.append(")");
|
||||
|
||||
if(sqlFilter.toString().trim().equals("()")){
|
||||
return null;
|
||||
}
|
||||
|
||||
return sqlFilter.toString();
|
||||
}
|
||||
|
||||
|
||||
// private String getSQLFilterTen(TenUserEntity user, JoinPoint point){
|
||||
// MethodSignature signature = (MethodSignature) point.getSignature();
|
||||
// DataFilter dataFilter = signature.getMethod().getAnnotation(DataFilter.class);
|
||||
// //获取表的别名
|
||||
// String tableAlias = dataFilter.tableAlias();
|
||||
// if(StringUtils.isNotBlank(tableAlias)){
|
||||
// tableAlias += ".";
|
||||
// }
|
||||
//
|
||||
// //部门ID列表
|
||||
// Set<Long> deptIdList = new HashSet<>();
|
||||
//
|
||||
// //用户角色对应的部门ID列表
|
||||
// List<Long> roleIdList = tenUserRoleService.queryRoleIdList(user.getUserId(),user.getTenantId()+"");
|
||||
// if(roleIdList.size() > 0){
|
||||
// List<Long> userDeptIdList = tenRoleDeptService.queryDeptIdList(roleIdList.toArray(new Long[roleIdList.size()]),user.getTenantId()+"");
|
||||
// deptIdList.addAll(userDeptIdList);
|
||||
// }
|
||||
//
|
||||
// //当前部门
|
||||
// deptIdList.add(user.getDeptId());
|
||||
//
|
||||
// //用户子部门ID列表
|
||||
// if(dataFilter.subDept()){
|
||||
// List<Long> subDeptIdList = tenDeptService.getSubDeptIdList(user.getDeptId(),user.getTenantId()+"");
|
||||
// deptIdList.addAll(subDeptIdList);
|
||||
// }
|
||||
//
|
||||
// StringBuilder sqlFilter = new StringBuilder();
|
||||
// sqlFilter.append(" (");
|
||||
//
|
||||
// if(deptIdList.size() > 0){
|
||||
// sqlFilter.append(tableAlias).append(dataFilter.deptId()).append(" in(").append(StringUtils.join(deptIdList, ",")).append(")");
|
||||
// }
|
||||
//
|
||||
// //没有本部门数据权限,也能查询本人数据
|
||||
// if(dataFilter.user()){
|
||||
// if(deptIdList.size() > 0){
|
||||
// sqlFilter.append(" or ");
|
||||
// }
|
||||
// sqlFilter.append(tableAlias).append(dataFilter.userId()).append("=").append(user.getUserId());
|
||||
// }
|
||||
//
|
||||
// sqlFilter.append(")");
|
||||
//
|
||||
// if(sqlFilter.toString().trim().equals("()")){
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// return sqlFilter.toString();
|
||||
// }
|
||||
}
|
|
@ -0,0 +1,103 @@
|
|||
|
||||
|
||||
package net.shapelight.common.aspect;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
|
||||
|
||||
import net.shapelight.common.annotation.SysLog;
|
||||
import net.shapelight.common.utils.IpUtils;
|
||||
import net.shapelight.modules.sys.entity.SysLogEntity;
|
||||
import net.shapelight.modules.sys.entity.SysUserEntity;
|
||||
import net.shapelight.modules.sys.service.SysLogService;
|
||||
import net.shapelight.common.utils.HttpContextUtils;
|
||||
import net.shapelight.common.utils.IPUtils;
|
||||
|
||||
import net.shapelight.common.annotation.SysLog;
|
||||
import net.shapelight.common.utils.HttpContextUtils;
|
||||
import net.shapelight.modules.sys.entity.SysUserEntity;
|
||||
import org.apache.shiro.SecurityUtils;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 系统日志,切面处理类
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class SysLogAspect {
|
||||
@Autowired
|
||||
private SysLogService sysLogService;
|
||||
|
||||
@Pointcut("@annotation(net.shapelight.common.annotation.SysLog)")
|
||||
public void logPointCut() {
|
||||
|
||||
}
|
||||
|
||||
@Around("logPointCut()")
|
||||
public Object around(ProceedingJoinPoint point) throws Throwable {
|
||||
long beginTime = System.currentTimeMillis();
|
||||
//执行方法
|
||||
Object result = point.proceed();
|
||||
//执行时长(毫秒)
|
||||
long time = System.currentTimeMillis() - beginTime;
|
||||
|
||||
//保存日志
|
||||
saveSysLog(point, time);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
|
||||
SysLogEntity sysLog = new SysLogEntity();
|
||||
SysLog syslog = method.getAnnotation(SysLog.class);
|
||||
if(syslog != null){
|
||||
//注解上的描述
|
||||
sysLog.setOperation(syslog.value());
|
||||
}
|
||||
|
||||
//请求的方法名
|
||||
String className = joinPoint.getTarget().getClass().getName();
|
||||
String methodName = signature.getName();
|
||||
sysLog.setMethod(className + "." + methodName + "()");
|
||||
|
||||
//请求的参数
|
||||
Object[] args = joinPoint.getArgs();
|
||||
try{
|
||||
String params = new Gson().toJson(args[0]);
|
||||
sysLog.setParams(params);
|
||||
}catch (Exception e){
|
||||
|
||||
}
|
||||
|
||||
//获取request
|
||||
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
|
||||
//设置IP地址
|
||||
// sysLog.setIp(IPUtils.getIpAddr(request));
|
||||
sysLog.setIp(IpUtils.getIpAddr(request));
|
||||
|
||||
|
||||
//用户名
|
||||
String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername();
|
||||
sysLog.setUsername(username);
|
||||
|
||||
sysLog.setTime(time);
|
||||
sysLog.setCreateDate(new Date());
|
||||
//保存系统日志
|
||||
sysLogService.save(sysLog);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,95 @@
|
|||
package net.shapelight.common.aspect;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import net.shapelight.common.annotation.TenLog;
|
||||
import net.shapelight.common.utils.HttpContextUtils;
|
||||
import net.shapelight.common.utils.IPUtils;
|
||||
import net.shapelight.modules.sys.entity.SysUserEntity;
|
||||
import net.shapelight.modules.ten.entity.TenLogEntity;
|
||||
import net.shapelight.modules.ten.service.TenLogService;
|
||||
import org.apache.shiro.SecurityUtils;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 系统日志,切面处理类
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class TenLogAspect {
|
||||
@Autowired
|
||||
private TenLogService tenLogService;
|
||||
|
||||
@Pointcut("@annotation(net.shapelight.common.annotation.TenLog)")
|
||||
public void logPointCut() {
|
||||
|
||||
}
|
||||
|
||||
@Around("logPointCut()")
|
||||
public Object around(ProceedingJoinPoint point) throws Throwable {
|
||||
long beginTime = System.currentTimeMillis();
|
||||
//执行方法
|
||||
Object result = point.proceed();
|
||||
//执行时长(毫秒)
|
||||
long time = System.currentTimeMillis() - beginTime;
|
||||
|
||||
//保存日志
|
||||
saveSysLog(point, time);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
|
||||
TenLogEntity tenLogEntity = new TenLogEntity();
|
||||
TenLog tenlog = method.getAnnotation(TenLog.class);
|
||||
if(tenlog != null){
|
||||
//注解上的描述
|
||||
tenLogEntity.setOperation(tenlog.value());
|
||||
}
|
||||
|
||||
//请求的方法名
|
||||
String className = joinPoint.getTarget().getClass().getName();
|
||||
String methodName = signature.getName();
|
||||
tenLogEntity.setMethod(className + "." + methodName + "()");
|
||||
|
||||
//请求的参数
|
||||
Object[] args = joinPoint.getArgs();
|
||||
try{
|
||||
String params = new Gson().toJson(args[0]);
|
||||
tenLogEntity.setParams(params);
|
||||
}catch (Exception e){
|
||||
|
||||
}
|
||||
|
||||
//获取request
|
||||
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
|
||||
//设置IP地址
|
||||
tenLogEntity.setIp(IPUtils.getIpAddr(request));
|
||||
|
||||
//用户名
|
||||
SysUserEntity sysUserEntity= ((SysUserEntity) SecurityUtils.getSubject().getPrincipal());
|
||||
|
||||
String username = sysUserEntity.getUsername();
|
||||
tenLogEntity.setUsername(username);
|
||||
|
||||
tenLogEntity.setTime(time);
|
||||
tenLogEntity.setCreateDate(new Date());
|
||||
tenLogEntity.setTenantId(sysUserEntity.getTenantId());
|
||||
//保存系统日志
|
||||
tenLogService.add(tenLogEntity);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package net.shapelight.common.base;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 基础模型
|
||||
*/
|
||||
@Data
|
||||
public class BaseEntity {
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@ApiModelProperty("创建时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private Date createTime;
|
||||
/**
|
||||
* 创建人
|
||||
*/
|
||||
@ApiModelProperty("创建人")
|
||||
private String createBy;
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
@ApiModelProperty("更新时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
|
||||
private Date lastUpdateTime;
|
||||
/**
|
||||
* 更新人
|
||||
*/
|
||||
@ApiModelProperty("更新人")
|
||||
private String lastUpdateBy;
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package net.shapelight.common.base;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Data
|
||||
public class BasePageDTO {
|
||||
|
||||
private Long current;
|
||||
|
||||
private Long size;
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package net.shapelight.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class CorsConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedOrigins("*")
|
||||
// .allowedOriginPatterns("*")
|
||||
.allowCredentials(true)
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||
.maxAge(3600);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
|
||||
|
||||
package net.shapelight.common.config;
|
||||
|
||||
import net.shapelight.common.xss.XssFilter;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.filter.DelegatingFilterProxy;
|
||||
|
||||
import javax.servlet.DispatcherType;
|
||||
|
||||
/**
|
||||
* Filter配置
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Configuration
|
||||
public class FilterConfig {
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean shiroFilterRegistration() {
|
||||
FilterRegistrationBean registration = new FilterRegistrationBean();
|
||||
registration.setFilter(new DelegatingFilterProxy("shiroFilter"));
|
||||
//该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理
|
||||
registration.addInitParameter("targetFilterLifecycle", "true");
|
||||
registration.setEnabled(true);
|
||||
registration.setOrder(Integer.MAX_VALUE - 1);
|
||||
registration.addUrlPatterns("/*");
|
||||
return registration;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean xssFilterRegistration() {
|
||||
FilterRegistrationBean registration = new FilterRegistrationBean();
|
||||
registration.setDispatcherTypes(DispatcherType.REQUEST);
|
||||
registration.setFilter(new XssFilter());
|
||||
registration.addUrlPatterns("/*");
|
||||
registration.setName("xssFilter");
|
||||
registration.setOrder(Integer.MAX_VALUE);
|
||||
return registration;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
|
||||
|
||||
package net.shapelight.common.config;
|
||||
|
||||
import net.shapelight.modules.sys.shiro.ShiroTag;
|
||||
import net.shapelight.modules.sys.shiro.ShiroTag;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* Freemarker配置
|
||||
*
|
||||
*
|
||||
*/
|
||||
//@Configuration
|
||||
public class FreemarkerConfig {
|
||||
|
||||
//@Bean
|
||||
/*public FreeMarkerConfigurer freeMarkerConfigurer(ShiroTag shiroTag){
|
||||
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
|
||||
configurer.setTemplateLoaderPath("classpath:/templates");
|
||||
Map<String, Object> variables = new HashMap<>(1);
|
||||
variables.put("shiro", shiroTag);
|
||||
configurer.setFreemarkerVariables(variables);
|
||||
|
||||
Properties settings = new Properties();
|
||||
settings.setProperty("default_encoding", "utf-8");
|
||||
settings.setProperty("number_format", "0.##");
|
||||
configurer.setFreemarkerSettings(settings);
|
||||
return configurer;
|
||||
}*/
|
||||
|
||||
}
|
|
@ -0,0 +1,109 @@
|
|||
package net.shapelight.common.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
/*
|
||||
global:
|
||||
http_flag: http
|
||||
file_path:
|
||||
static-locations: /home/shapelight/sl_site
|
||||
static-user_path: userdata
|
||||
#log_file: snail_develop.log
|
||||
#http_flag: http
|
||||
user_path: /home/shapelight/Snail_develop/UserData
|
||||
common_path: /home/shapelight/Snail_develop/Common
|
||||
wx_code_path: /home/shapelight/Snail_develop/WxCode
|
||||
doc_path: /home/shapelight/Snail_develop/Doc
|
||||
apk_path: /home/shapelight/Snail_develop/Apk
|
||||
ten_pic: pic
|
||||
ten_wx: wx
|
||||
ten_xlsx: xlsx
|
||||
ten_song: song
|
||||
ten_logo: logo
|
||||
ten_member_org: member_org
|
||||
ten_member_face: member_face
|
||||
ten_visitor_org: visitor_org
|
||||
ten_visitor_face: visitor_face
|
||||
ten_member_rec_org: member_rec_org
|
||||
ten_member_rec_face: member_rec_face
|
||||
ten_visitor_rec_org: visitor_rec_org
|
||||
ten_visitor_rec_face: visitor_rec_face
|
||||
url:
|
||||
#addr: 192.168.1.50:9902
|
||||
url_img: 192.168.1.50:9903
|
||||
url_out: 192.168.1.50:9903
|
||||
url_license: 39.96.9.232:3389
|
||||
upload_zip:
|
||||
protocal: http://
|
||||
ip: 127.0.0.1
|
||||
port: 8001
|
||||
zippath: /home/shapelight/DataBase/studentOrg
|
||||
small-face-path: /home/shapelight/DataBase/studentFace
|
||||
*/
|
||||
|
||||
@Component
|
||||
@Data
|
||||
public class GlobalValue {
|
||||
|
||||
@Value("${global.http_flag}")
|
||||
private String httpFlag;
|
||||
@Value("${global.file_path.static-locations}")
|
||||
private String staticLocations;
|
||||
@Value("${global.file_path.temp_dir}")
|
||||
private String tempDir;
|
||||
@Value("${global.file_path.images_dir}")
|
||||
private String imagesDir;
|
||||
@Value("${global.file_path.apk_dir}")
|
||||
private String apkDir;
|
||||
@Value("${global.file_path.opt_dir}")
|
||||
private String optDir;
|
||||
|
||||
@Value("${spring.mqtt.username}")
|
||||
private String mqttUsername;
|
||||
@Value("${spring.mqtt.password}")
|
||||
private String mqttPassword;
|
||||
@Value("${spring.mqtt.url}")
|
||||
private String mqttUrl;
|
||||
@Value("${spring.mqtt.api}")
|
||||
private String mqttApi;
|
||||
|
||||
@Value("${global.minio.endpoint}")
|
||||
private String minioEndpoint;
|
||||
@Value("${global.minio.port}")
|
||||
private String minioPort;
|
||||
@Value("${global.minio.accessKey}")
|
||||
private String minioAccessKey;
|
||||
@Value("${global.minio.secretKey}")
|
||||
private String minioSecretKey;
|
||||
@Value("${global.minio.bucketName}")
|
||||
private String minioBucketName;
|
||||
|
||||
@Value("${global.minio.path}")
|
||||
private String minioPath;
|
||||
|
||||
|
||||
@Value("${global.device.appId}")
|
||||
private String devAppId;
|
||||
@Value("${global.device.appSecret}")
|
||||
private String devAppSecret;
|
||||
|
||||
@Value("${global.wx.appid}")
|
||||
private String wxAppid;
|
||||
@Value("${global.wx.secret}")
|
||||
private String wxSecret;
|
||||
@Value("${global.wx.url}")
|
||||
private String wxUrl;
|
||||
@Value("${global.wx.mchid}")
|
||||
private String mchid;
|
||||
|
||||
@Value("${global.app.key}")
|
||||
private String appKey;
|
||||
@Value("${global.app.secret}")
|
||||
private String appSecret;
|
||||
|
||||
@Value("${global.qingju.accountNumber}")
|
||||
public String accountNumber;
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
|
||||
|
||||
package net.shapelight.common.config;
|
||||
|
||||
import com.google.code.kaptcha.impl.DefaultKaptcha;
|
||||
import com.google.code.kaptcha.util.Config;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
|
||||
/**
|
||||
* 生成验证码配置
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Configuration
|
||||
public class KaptchaConfig {
|
||||
|
||||
@Bean
|
||||
public DefaultKaptcha producer() {
|
||||
Properties properties = new Properties();
|
||||
properties.put("kaptcha.border", "no");
|
||||
properties.put("kaptcha.textproducer.font.color", "black");
|
||||
properties.put("kaptcha.textproducer.char.space", "5");
|
||||
properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
|
||||
Config config = new Config(properties);
|
||||
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
|
||||
defaultKaptcha.setConfig(config);
|
||||
return defaultKaptcha;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package net.shapelight.common.config;
|
||||
|
||||
import io.minio.MinioClient;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 对象存储工具类
|
||||
*/
|
||||
@Component
|
||||
public class MinioConfig {
|
||||
@Autowired
|
||||
private GlobalValue globalValue;
|
||||
|
||||
public String getBucketName(){
|
||||
return globalValue.getMinioBucketName();
|
||||
}
|
||||
@Bean("minioClient")
|
||||
public MinioClient minioClient(){
|
||||
MinioClient minioClient=null;
|
||||
try {
|
||||
minioClient = new MinioClient(globalValue.getMinioEndpoint(),
|
||||
// globalValue.getMinioPort(),
|
||||
globalValue.getMinioAccessKey(),
|
||||
globalValue.getMinioSecretKey());
|
||||
if (!minioClient.bucketExists(globalValue.getMinioBucketName())) {
|
||||
minioClient.makeBucket(globalValue.getMinioBucketName());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return minioClient;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,81 @@
|
|||
package net.shapelight.common.config;
|
||||
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.PutObjectOptions;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Base64;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class MinioUtils {
|
||||
@Autowired
|
||||
private MinioConfig minioConfig;
|
||||
@Autowired
|
||||
private MinioClient minioClient;
|
||||
|
||||
public String getFileBase64(String url){
|
||||
String base64Image = "";
|
||||
InputStream inStream = null;
|
||||
ByteArrayOutputStream outStream = null;
|
||||
try {
|
||||
minioClient.statObject(minioConfig.getBucketName(), url);
|
||||
inStream = minioClient.getObject(minioConfig.getBucketName(), url);
|
||||
outStream = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[1024];
|
||||
int length;
|
||||
while ((length = inStream.read(buffer)) != -1) {
|
||||
outStream.write(buffer, 0, length);
|
||||
}
|
||||
base64Image = Base64.getEncoder().encodeToString(outStream.toByteArray());
|
||||
} catch (Exception e) {
|
||||
log.error("Minio文件不存在:" + url);
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (inStream != null) {
|
||||
try {
|
||||
inStream.close();
|
||||
} catch (IOException e) {
|
||||
log.error("inputStream close IOException:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
if (outStream != null) {
|
||||
try {
|
||||
outStream.close();
|
||||
} catch (IOException e) {
|
||||
log.error("outStream close IOException:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
return base64Image;
|
||||
}
|
||||
|
||||
public boolean saveFileByBase64(String fileBase64,String fileName,String contentType){
|
||||
if(fileBase64!=null && !fileBase64.isEmpty()){
|
||||
try {
|
||||
byte[] b = Base64.getDecoder().decode(fileBase64.replace("\n", ""));
|
||||
InputStream inputStream = new ByteArrayInputStream(b);
|
||||
PutObjectOptions putObjectOptions = new PutObjectOptions(b.length, -1);
|
||||
// putObjectOptions.setContentType("image/jpeg");
|
||||
putObjectOptions.setContentType(contentType);
|
||||
minioClient.putObject(
|
||||
minioConfig.getBucketName(), fileName, inputStream, putObjectOptions);
|
||||
inputStream.close();
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
log.error(e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}else{
|
||||
log.debug("Minio文件base64为空,不能写入");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
|
||||
|
||||
package net.shapelight.common.config;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import net.shapelight.common.handler.CustomizeTableNameHandler;
|
||||
import net.shapelight.common.handler.TimeHandler;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
|
||||
/**
|
||||
* mybatis-plus配置
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Configuration
|
||||
public class MybatisPlusConfig {
|
||||
|
||||
|
||||
@Bean
|
||||
public TimeHandler metaObjectHandler() {
|
||||
return new TimeHandler();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 分表插件
|
||||
*/
|
||||
// 最新版
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
// 分表插件
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
|
||||
DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
|
||||
dynamicTableNameInnerInterceptor.setTableNameHandler(
|
||||
//可以传多个表名参数,指定哪些表使用MonthTableNameHandler处理表名称
|
||||
new CustomizeTableNameHandler("ten_person_extract,mobile_device,mobile_package_order,mobile_call_logs")
|
||||
);
|
||||
|
||||
//以拦截器的方式处理表名称
|
||||
interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
|
||||
return interceptor;
|
||||
}
|
||||
// @Bean
|
||||
// public ISqlInjector sqlInjector() {
|
||||
// return new LogicSqlInjector();
|
||||
// }
|
||||
|
||||
/*// @Bean
|
||||
// public PaginationInterceptor paginationInterceptor() {
|
||||
// PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
|
||||
// DynamicTableNameParser dynamicTableNameParser = new DynamicTableNameParser();
|
||||
// // 创建SQL解析器集合
|
||||
// List<ISqlParser> sqlParserList = new ArrayList<>();
|
||||
//
|
||||
// Map<String,ITableNameHandler> tableNameHandlerMap = new HashMap<>();
|
||||
// // Map的key就是需要替换的原始表名
|
||||
// tableNameHandlerMap.put("ten_cell",new ITableNameHandler(){
|
||||
// @Override
|
||||
// public String dynamicTableName(MetaObject metaObject, String sql, String tableName) {
|
||||
// // 自定义表名规则,或者从配置文件、request上下文中读取
|
||||
//
|
||||
// // 假设这里的用户表根据年份来进行分表操作
|
||||
// Date date = new Date();
|
||||
// String year = String.format("%tY", date);
|
||||
// // 返回最后需要操作的表名,sys_user_2019
|
||||
// return "ten_cell_" + year;
|
||||
// }
|
||||
// });
|
||||
//
|
||||
// tableNameHandlerMap.put("ten_cell",new ITableNameHandler(){
|
||||
// @Override
|
||||
// public String dynamicTableName(MetaObject metaObject, String sql, String tableName) {
|
||||
// // 自定义表名规则,或者从配置文件、request上下文中读取
|
||||
//
|
||||
// // 假设这里的用户表根据年份来进行分表操作
|
||||
// Date date = new Date();
|
||||
// String year = String.format("%tY", date);
|
||||
// // 返回最后需要操作的表名,sys_user_2019
|
||||
// return "ten_cell_" + 2019;
|
||||
// }
|
||||
// });
|
||||
//
|
||||
//
|
||||
// dynamicTableNameParser.setTableNameHandlerMap(tableNameHandlerMap);
|
||||
// sqlParserList.add(dynamicTableNameParser);
|
||||
// paginationInterceptor.setSqlParserList(sqlParserList);
|
||||
//
|
||||
//// dynamicTableNameParser.setTableNameHandlerMap(new HashMap<String, ITableNameHandler>(2) {{
|
||||
//// put("sysUserEntity", (metaObject, sql, tableName) -> {
|
||||
//// // metaObject 可以获取传入参数,这里实现你自己的动态规则
|
||||
//// String year = "_2018";
|
||||
//// int random = new Random().nextInt(10);
|
||||
//// if (random % 2 == 1) {
|
||||
//// year = "_2019";
|
||||
//// }
|
||||
//// return tableName + year;
|
||||
//// return tableName + (String)metaObject.getValue("schema");
|
||||
//// });
|
||||
//// }});
|
||||
//// paginationInterceptor.setSqlParserList(Collections.singletonList(dynamicTableNameParser));
|
||||
// return paginationInterceptor;
|
||||
// }*/
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package net.shapelight.common.config;
|
||||
|
||||
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@Configuration
|
||||
public class RestTemplateConfig {
|
||||
@Bean
|
||||
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
|
||||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
||||
factory.setConnectTimeout(15000);
|
||||
factory.setReadTimeout(5000);
|
||||
return factory;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,152 @@
|
|||
|
||||
|
||||
package net.shapelight.common.config;
|
||||
|
||||
import net.shapelight.modules.sys.oauth2.OAuth2Filter;
|
||||
import net.shapelight.modules.sys.oauth2.OAuth2Realm;
|
||||
import org.apache.shiro.cache.ehcache.EhCacheManager;
|
||||
import org.apache.shiro.mgt.SecurityManager;
|
||||
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
|
||||
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
|
||||
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
|
||||
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.event.ContextRefreshedEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Shiro的配置文件
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Configuration
|
||||
public class ShiroConfig {
|
||||
|
||||
/**
|
||||
* 单机环境,session交给shiro管理
|
||||
*/
|
||||
/*
|
||||
@Bean
|
||||
@ConditionalOnProperty(prefix = "shapelight", name = "cluster", havingValue = "false")
|
||||
public DefaultWebSessionManager sessionManager(@Value("${shapelight.globalSessionTimeout:3600}") long globalSessionTimeout){
|
||||
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
|
||||
sessionManager.setSessionValidationSchedulerEnabled(true);
|
||||
sessionManager.setSessionIdUrlRewritingEnabled(false);
|
||||
sessionManager.setSessionValidationInterval(globalSessionTimeout * 1000);
|
||||
sessionManager.setGlobalSessionTimeout(globalSessionTimeout * 1000);
|
||||
|
||||
return sessionManager;
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* 集群环境,session交给spring-session管理
|
||||
*/
|
||||
/*@Bean
|
||||
@ConditionalOnProperty(prefix = "shapelight", name = "cluster", havingValue = "true")
|
||||
public ServletContainerSessionManager servletContainerSessionManager() {
|
||||
return new ServletContainerSessionManager();
|
||||
}*/
|
||||
|
||||
|
||||
/*public SecurityManager securityManager(UserRealm userRealm, SessionManager sessionManager) {
|
||||
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
|
||||
securityManager.setRealm(userRealm);
|
||||
securityManager.setSessionManager(sessionManager);
|
||||
securityManager.setRememberMeManager(null);
|
||||
|
||||
return securityManager;
|
||||
}*/
|
||||
@Bean("securityManager")
|
||||
public SecurityManager securityManager(OAuth2Realm oAuth2Realm) {
|
||||
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
|
||||
securityManager.setCacheManager(new EhCacheManager());
|
||||
securityManager.setRealm(oAuth2Realm);
|
||||
securityManager.setRememberMeManager(null);
|
||||
return securityManager;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
|
||||
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
|
||||
shiroFilter.setSecurityManager(securityManager);
|
||||
shiroFilter.setLoginUrl("/login.html");
|
||||
shiroFilter.setUnauthorizedUrl("/");
|
||||
|
||||
Map<String, String> filterMap = new LinkedHashMap<>();
|
||||
filterMap.put("/swagger/**", "anon");
|
||||
filterMap.put("/v2/api-docs", "anon");
|
||||
filterMap.put("/swagger-ui.html", "anon");
|
||||
filterMap.put("/webjars/**", "anon");
|
||||
filterMap.put("/swagger-resources/**", "anon");
|
||||
|
||||
filterMap.put("/statics/**", "anon");
|
||||
filterMap.put("/login.html", "anon");
|
||||
filterMap.put("/sys/login", "anon");
|
||||
filterMap.put("/favicon.ico", "anon");
|
||||
filterMap.put("/captcha.jpg", "anon");
|
||||
filterMap.put("/**", "authc");
|
||||
shiroFilter.setFilterChainDefinitionMap(filterMap);
|
||||
|
||||
return shiroFilter;
|
||||
}*/
|
||||
@Bean("shiroFilter")
|
||||
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
|
||||
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
|
||||
shiroFilter.setSecurityManager(securityManager);
|
||||
|
||||
//oauth过滤
|
||||
Map<String, Filter> filters = new HashMap<>();
|
||||
filters.put("oauth2", new OAuth2Filter());
|
||||
shiroFilter.setFilters(filters);
|
||||
|
||||
Map<String, String> filterMap = new LinkedHashMap<>();
|
||||
// filterMap.put("/ten/member/uploadExcel", "anon");
|
||||
// filterMap.put("/ten/member/uploadImage", "anon");
|
||||
// filterMap.put("/ten/member/uploadImageBatch", "anon");
|
||||
// filterMap.put("/ten/member/uploadZip", "anon");
|
||||
filterMap.put("/webjars/**", "anon");
|
||||
filterMap.put("/druid/**", "anon");
|
||||
filterMap.put("/app/**", "anon");
|
||||
filterMap.put("/parent/app/**", "anon");
|
||||
filterMap.put("/api/**", "anon");
|
||||
filterMap.put("/images/**", "anon");//网站上传的图片files
|
||||
filterMap.put("/files/**", "anon");//网站上传的图片files
|
||||
filterMap.put("/sys/login", "anon");
|
||||
filterMap.put("/sys/config/listapp", "anon");
|
||||
filterMap.put("/sys/appversion/listapp", "anon");
|
||||
filterMap.put("/swagger/**", "anon");
|
||||
filterMap.put("/v2/api-docs", "anon");
|
||||
filterMap.put("/swagger-ui.html", "anon");
|
||||
filterMap.put("/swagger-resources/**", "anon");
|
||||
filterMap.put("/captcha.jpg", "anon");
|
||||
filterMap.put("/mobile/device/group/export", "anon");
|
||||
// filterMap.put("/aaa.txt", "anon");
|
||||
filterMap.put("/**", "oauth2");
|
||||
|
||||
|
||||
shiroFilter.setFilterChainDefinitionMap(filterMap);
|
||||
|
||||
return shiroFilter;
|
||||
}
|
||||
|
||||
@Bean("lifecycleBeanPostProcessor")
|
||||
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
|
||||
return new LifecycleBeanPostProcessor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
|
||||
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
|
||||
advisor.setSecurityManager(securityManager);
|
||||
return advisor;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
|
||||
|
||||
package net.shapelight.common.config;
|
||||
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import springfox.documentation.builders.ApiInfoBuilder;
|
||||
import springfox.documentation.builders.ParameterBuilder;
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
import springfox.documentation.schema.ModelRef;
|
||||
import springfox.documentation.service.ApiInfo;
|
||||
import springfox.documentation.service.Parameter;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Swagger配置
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Configuration
|
||||
@EnableSwagger2
|
||||
public class SwaggerConfig{
|
||||
|
||||
@Bean
|
||||
public Docket createRestApi() {
|
||||
ParameterBuilder tokenPar = new ParameterBuilder();
|
||||
List<Parameter> pars = new ArrayList<Parameter>();
|
||||
tokenPar.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
|
||||
pars.add(tokenPar.build());
|
||||
return new Docket(DocumentationType.SWAGGER_2)
|
||||
.apiInfo(apiInfo())
|
||||
.select()
|
||||
//加了ApiOperation注解的类,生成接口文档
|
||||
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
|
||||
//包下的类,生成接口文档
|
||||
//.apis(RequestHandlerSelectors.basePackage("net.shapelight.modules.job.controller"))
|
||||
.paths(PathSelectors.any())
|
||||
.build()
|
||||
.globalOperationParameters(pars);
|
||||
}
|
||||
|
||||
private ApiInfo apiInfo() {
|
||||
return new ApiInfoBuilder()
|
||||
.title("智慧社区平台")
|
||||
.description("后台接口文档")
|
||||
.termsOfServiceUrl("https://www.shapelight.net")
|
||||
.version("2.0.0")
|
||||
.build();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package net.shapelight.common.config;
|
||||
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import org.apache.catalina.connector.Connector;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
|
||||
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
|
||||
|
||||
@Configuration
|
||||
public class TomcatConfig {
|
||||
|
||||
// @Value("${server.http.port}")
|
||||
// private int httpPort;
|
||||
|
||||
@Value("${http.port}")
|
||||
private Integer port;
|
||||
|
||||
@Bean
|
||||
public ServletWebServerFactory servletContainer() {
|
||||
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
|
||||
// 配置http
|
||||
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
|
||||
connector.setPort(port);
|
||||
|
||||
tomcat.addAdditionalTomcatConnectors(connector); // 添加http
|
||||
return tomcat;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
|
||||
|
||||
package net.shapelight.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* WebMvc配置
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
|
||||
|
||||
//swagger增加url映射
|
||||
registry.addResourceHandler("swagger-ui.html")
|
||||
.addResourceLocations("classpath:/META-INF/resources/");
|
||||
registry.addResourceHandler("/webjars/**")
|
||||
.addResourceLocations("classpath:/META-INF/resources/webjars/");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package net.shapelight.common.config;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class WxMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
|
||||
public WxMappingJackson2HttpMessageConverter(){
|
||||
List<MediaType> mediaTypes = new ArrayList<>();
|
||||
mediaTypes.add(MediaType.IMAGE_JPEG);
|
||||
setSupportedMediaTypes(mediaTypes);//
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
//package net.shapelight.common.config.shard;
|
||||
//
|
||||
//import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
|
||||
//import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
//import java.util.Collection;
|
||||
//
|
||||
///**
|
||||
// * 数据库映射计算
|
||||
// */
|
||||
//public class DataSourceAlg implements PreciseShardingAlgorithm<String> {
|
||||
//
|
||||
// private static Logger LOG = LoggerFactory.getLogger(DataSourceAlg.class);
|
||||
// @Override
|
||||
// public String doSharding(Collection<String> names, PreciseShardingValue<String> value) {
|
||||
// LOG.debug("分库算法参数 {},{}",names,value);
|
||||
// //int hash = HashUtil.rsHash(String.valueOf(value.getValue()));
|
||||
// //return "ds_" + ((hash % 2) + 2) ;
|
||||
// return "ds_0";
|
||||
// }
|
||||
//}
|
|
@ -0,0 +1,15 @@
|
|||
package net.shapelight.common.config.shard;
|
||||
|
||||
public class HashUtil {
|
||||
|
||||
public static int rsHash(String value) {
|
||||
int one = 378551;
|
||||
int two = 63689;
|
||||
int hash = 0;
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
hash = hash * two + value.charAt(i);
|
||||
two = two * one;
|
||||
}
|
||||
return (hash & 0x7FFFFFFF);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,281 @@
|
|||
//package net.shapelight.common.config.shard;
|
||||
//
|
||||
//import com.alibaba.druid.pool.DruidDataSource;
|
||||
//import io.shardingsphere.api.config.rule.ShardingRuleConfiguration;
|
||||
//import io.shardingsphere.api.config.rule.TableRuleConfiguration;
|
||||
//import io.shardingsphere.api.config.strategy.StandardShardingStrategyConfiguration;
|
||||
//import io.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
|
||||
//import org.apache.ibatis.session.SqlSessionFactory;
|
||||
//import org.mybatis.spring.SqlSessionFactoryBean;
|
||||
//import org.springframework.beans.factory.annotation.Autowired;
|
||||
//import org.springframework.beans.factory.annotation.Value;
|
||||
//import org.springframework.context.annotation.Bean;
|
||||
//import org.springframework.context.annotation.Configuration;
|
||||
//import org.springframework.jdbc.core.JdbcTemplate;
|
||||
//import javax.sql.DataSource;
|
||||
//import java.util.HashMap;
|
||||
//import java.util.LinkedHashMap;
|
||||
//import java.util.Map;
|
||||
//import java.util.Properties;
|
||||
//
|
||||
///**
|
||||
// * 数据库分库分表配置
|
||||
// */
|
||||
//@Configuration
|
||||
//public class ShardJdbcConfig {
|
||||
//
|
||||
// @Value("${spring.datasource.dataOne.druid.url}")
|
||||
// private String dbUrl1;
|
||||
// @Value("${spring.datasource.dataOne.druid.username}")
|
||||
// private String username1;
|
||||
// @Value("${spring.datasource.dataOne.druid.password}")
|
||||
// private String password1;
|
||||
// @Value("${spring.datasource.dataOne.druid.driverClassName}")
|
||||
// private String driverClassName1;
|
||||
// @Value("${spring.datasource.dataOne.druid.initial-size}")
|
||||
// private int initialSize1;
|
||||
// @Value("${spring.datasource.dataOne.druid.max-active}")
|
||||
// private int maxActive1;
|
||||
// @Value("${spring.datasource.dataOne.druid.min-idle}")
|
||||
// private int minIdle1;
|
||||
// @Value("${spring.datasource.dataOne.druid.max-wait}")
|
||||
// private int maxWait1;
|
||||
// @Value("${spring.datasource.dataOne.druid.pool-prepared-statements}")
|
||||
// private boolean poolPreparedStatements1;
|
||||
// @Value("${spring.datasource.dataOne.druid.max-pool-prepared-statement-per-connection-size}")
|
||||
// private int maxPoolPreparedStatementPerConnectionSize1;
|
||||
// @Value("${spring.datasource.dataOne.druid.time-between-eviction-runs-millis}")
|
||||
// private int timeBetweenEvictionRunsMillis1;
|
||||
// @Value("${spring.datasource.dataOne.druid.min-evictable-idle-time-millis}")
|
||||
// private int minEvictableIdleTimeMillis1;
|
||||
// @Value("${spring.datasource.dataOne.druid.max-evictable-idle-time-millis}")
|
||||
// private int maxEvictableIdleTimeMillis1;
|
||||
// @Value("${spring.datasource.dataOne.druid.validation-query}")
|
||||
// private String validationQuery1;
|
||||
// @Value("${spring.datasource.dataOne.druid.test-while-idle}")
|
||||
// private boolean testWhileIdle1;
|
||||
// @Value("${spring.datasource.dataOne.druid.test-on-borrow}")
|
||||
// private boolean testOnBorrow1;
|
||||
// @Value("${spring.datasource.dataOne.druid.test-on-return}")
|
||||
// private boolean testOnReturn1;
|
||||
// @Value("{spring.datasource.dataOne.druid.connection-properties}")
|
||||
// private String connectionProperties1;
|
||||
// @Bean
|
||||
// public DruidDataSource dataOneSource() {
|
||||
// DruidDataSource datasource = new DruidDataSource();
|
||||
// datasource.setUrl(dbUrl1);
|
||||
// datasource.setUsername(username1);
|
||||
// datasource.setPassword(password1);
|
||||
// datasource.setDriverClassName(driverClassName1);
|
||||
// datasource.setInitialSize(initialSize1);
|
||||
// datasource.setMinIdle(minIdle1);
|
||||
// datasource.setMaxActive(maxActive1);
|
||||
// datasource.setMaxWait(maxWait1);
|
||||
// datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis1);
|
||||
// datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis1);
|
||||
// datasource.setMaxEvictableIdleTimeMillis(minEvictableIdleTimeMillis1);
|
||||
// datasource.setValidationQuery(validationQuery1);
|
||||
// datasource.setTestWhileIdle(testWhileIdle1);
|
||||
// datasource.setTestOnBorrow(testOnBorrow1);
|
||||
// datasource.setTestOnReturn(testOnReturn1);
|
||||
// datasource.setPoolPreparedStatements(poolPreparedStatements1);
|
||||
// datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize1);
|
||||
// datasource.setConnectionProperties(connectionProperties1);
|
||||
// return datasource;
|
||||
// }
|
||||
//
|
||||
//// @Value("${spring.datasource.dataTwo.druid.url}")
|
||||
//// private String dbUrl2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.username}")
|
||||
//// private String username2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.password}")
|
||||
//// private String password2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.driverClassName}")
|
||||
//// private String driverClassName2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.initial-size}")
|
||||
//// private int initialSize2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.max-active}")
|
||||
//// private int maxActive2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.min-idle}")
|
||||
//// private int minIdle2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.max-wait}")
|
||||
//// private int maxWait2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.pool-prepared-statements}")
|
||||
//// private boolean poolPreparedStatements2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.max-pool-prepared-statement-per-connection-size}")
|
||||
//// private int maxPoolPreparedStatementPerConnectionSize2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.time-between-eviction-runs-millis}")
|
||||
//// private int timeBetweenEvictionRunsMillis2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.min-evictable-idle-time-millis}")
|
||||
//// private int minEvictableIdleTimeMillis2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.max-evictable-idle-time-millis}")
|
||||
//// private int maxEvictableIdleTimeMillis2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.validation-query}")
|
||||
//// private String validationQuery2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.test-while-idle}")
|
||||
//// private boolean testWhileIdle2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.test-on-borrow}")
|
||||
//// private boolean testOnBorrow2;
|
||||
//// @Value("${spring.datasource.dataTwo.druid.test-on-return}")
|
||||
//// private boolean testOnReturn2;
|
||||
//// @Value("{spring.datasource.dataTwo.druid.connection-properties}")
|
||||
//// private String connectionProperties2;
|
||||
//// @Bean
|
||||
//// public DruidDataSource dataTwoSource() {
|
||||
//// DruidDataSource datasource = new DruidDataSource();
|
||||
//// datasource.setUrl(dbUrl2);
|
||||
//// datasource.setUsername(username2);
|
||||
//// datasource.setPassword(password2);
|
||||
//// datasource.setDriverClassName(driverClassName2);
|
||||
//// datasource.setInitialSize(initialSize2);
|
||||
//// datasource.setMinIdle(minIdle2);
|
||||
//// datasource.setMaxActive(maxActive2);
|
||||
//// datasource.setMaxWait(maxWait2);
|
||||
//// datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis2);
|
||||
//// datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis2);
|
||||
//// datasource.setMaxEvictableIdleTimeMillis(minEvictableIdleTimeMillis2);
|
||||
//// datasource.setValidationQuery(validationQuery2);
|
||||
//// datasource.setTestWhileIdle(testWhileIdle2);
|
||||
//// datasource.setTestOnBorrow(testOnBorrow2);
|
||||
//// datasource.setTestOnReturn(testOnReturn2);
|
||||
//// datasource.setPoolPreparedStatements(poolPreparedStatements2);
|
||||
//// datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize2);
|
||||
//// datasource.setConnectionProperties(connectionProperties2);
|
||||
//// return datasource;
|
||||
//// }
|
||||
////
|
||||
//// @Value("${spring.datasource.dataThree.druid.url}")
|
||||
//// private String dbUrl3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.username}")
|
||||
//// private String username3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.password}")
|
||||
//// private String password3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.driverClassName}")
|
||||
//// private String driverClassName3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.initial-size}")
|
||||
//// private int initialSize3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.max-active}")
|
||||
//// private int maxActive3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.min-idle}")
|
||||
//// private int minIdle3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.max-wait}")
|
||||
//// private int maxWait3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.pool-prepared-statements}")
|
||||
//// private boolean poolPreparedStatements3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.max-pool-prepared-statement-per-connection-size}")
|
||||
//// private int maxPoolPreparedStatementPerConnectionSize3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.time-between-eviction-runs-millis}")
|
||||
//// private int timeBetweenEvictionRunsMillis3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.min-evictable-idle-time-millis}")
|
||||
//// private int minEvictableIdleTimeMillis3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.max-evictable-idle-time-millis}")
|
||||
//// private int maxEvictableIdleTimeMillis3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.validation-query}")
|
||||
//// private String validationQuery3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.test-while-idle}")
|
||||
//// private boolean testWhileIdle3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.test-on-borrow}")
|
||||
//// private boolean testOnBorrow3;
|
||||
//// @Value("${spring.datasource.dataThree.druid.test-on-return}")
|
||||
//// private boolean testOnReturn3;
|
||||
//// @Value("{spring.datasource.dataThree.druid.connection-properties}")
|
||||
//// private String connectionProperties3;
|
||||
//// @Bean
|
||||
//// public DruidDataSource dataThreeSource() {
|
||||
//// DruidDataSource datasource = new DruidDataSource();
|
||||
//// datasource.setUrl(dbUrl3);
|
||||
//// datasource.setUsername(username3);
|
||||
//// datasource.setPassword(password3);
|
||||
//// datasource.setDriverClassName(driverClassName3);
|
||||
//// datasource.setInitialSize(initialSize3);
|
||||
//// datasource.setMinIdle(minIdle3);
|
||||
//// datasource.setMaxActive(maxActive3);
|
||||
//// datasource.setMaxWait(maxWait3);
|
||||
//// datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis3);
|
||||
//// datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis3);
|
||||
//// datasource.setMaxEvictableIdleTimeMillis(minEvictableIdleTimeMillis3);
|
||||
//// datasource.setValidationQuery(validationQuery3);
|
||||
//// datasource.setTestWhileIdle(testWhileIdle3);
|
||||
//// datasource.setTestOnBorrow(testOnBorrow3);
|
||||
//// datasource.setTestOnReturn(testOnReturn3);
|
||||
//// datasource.setPoolPreparedStatements(poolPreparedStatements3);
|
||||
//// datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize3);
|
||||
//// datasource.setConnectionProperties(connectionProperties3);
|
||||
//// return datasource;
|
||||
//// }
|
||||
//
|
||||
// /**
|
||||
// * JDBC操作配置
|
||||
// */
|
||||
// @Bean(name = "dataOneTemplate")
|
||||
// public JdbcTemplate dataOneTemplate (@Autowired DruidDataSource dataOneSource){
|
||||
// return new JdbcTemplate(dataOneSource) ;
|
||||
// }
|
||||
//// @Bean(name = "dataTwoTemplate")
|
||||
//// public JdbcTemplate dataTwoTemplate (@Autowired DruidDataSource dataTwoSource){
|
||||
//// return new JdbcTemplate(dataTwoSource) ;
|
||||
//// }
|
||||
//// @Bean(name = "dataThreeTemplate")
|
||||
//// public JdbcTemplate dataThreeTemplate (@Autowired DruidDataSource dataThreeSource){
|
||||
//// return new JdbcTemplate(dataThreeSource) ;
|
||||
//// }
|
||||
//
|
||||
// /**
|
||||
// * Shard-JDBC 分库配置
|
||||
// */
|
||||
//// @Bean
|
||||
//// public DataSource dataSource (@Autowired DruidDataSource dataOneSource,
|
||||
//// @Autowired DruidDataSource dataTwoSource,
|
||||
//// @Autowired DruidDataSource dataThreeSource) throws Exception {
|
||||
//// ShardingRuleConfiguration shardJdbcConfig = new ShardingRuleConfiguration();
|
||||
//// shardJdbcConfig.getTableRuleConfigs().add(getTableRule01());
|
||||
//// shardJdbcConfig.getTableRuleConfigs().add(getTableRule02());
|
||||
//// shardJdbcConfig.setDefaultDataSourceName("ds_0");
|
||||
//// Map<String,DataSource> dataMap = new LinkedHashMap<>() ;
|
||||
//// dataMap.put("ds_0",dataOneSource) ;
|
||||
//// dataMap.put("ds_2",dataTwoSource) ;
|
||||
//// dataMap.put("ds_3",dataThreeSource) ;
|
||||
//// Properties prop = new Properties();
|
||||
//// return ShardingDataSourceFactory.createDataSource(dataMap, shardJdbcConfig, new HashMap<>(), prop);
|
||||
//// }
|
||||
//
|
||||
//
|
||||
// @Bean(name = "dataSource")
|
||||
// public DataSource dataSource (@Autowired DruidDataSource dataOneSource) throws Exception {
|
||||
// ShardingRuleConfiguration shardJdbcConfig = new ShardingRuleConfiguration();
|
||||
// shardJdbcConfig.getTableRuleConfigs().add(getTableRule01());
|
||||
//// shardJdbcConfig.getTableRuleConfigs().add(getTableRule02());
|
||||
// shardJdbcConfig.setDefaultDataSourceName("ds_0");
|
||||
// Map<String,DataSource> dataMap = new LinkedHashMap<>() ;
|
||||
// dataMap.put("ds_0",dataOneSource) ;
|
||||
// Properties prop = new Properties();
|
||||
// return ShardingDataSourceFactory.createDataSource(dataMap, shardJdbcConfig, new HashMap<>(), prop);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Shard-JDBC 分表配置
|
||||
// */
|
||||
// private static TableRuleConfiguration getTableRule01() {
|
||||
// TableRuleConfiguration result = new TableRuleConfiguration();
|
||||
// result.setLogicTable("ten_person");
|
||||
// result.setActualDataNodes("ds_${2..3}.ten_person_${1..5}");
|
||||
// result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("id", new DataSourceAlg()));
|
||||
// result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("id", new TableOneAlg()));
|
||||
// return result;
|
||||
// }
|
||||
//// private static TableRuleConfiguration getTableRule02() {
|
||||
//// TableRuleConfiguration result = new TableRuleConfiguration();
|
||||
//// result.setLogicTable("table_two");
|
||||
//// result.setActualDataNodes("ds_${2..3}.table_two_${1..5}");
|
||||
//// result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("phone", new DataSourceAlg()));
|
||||
//// result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("phone", new TableTwoAlg()));
|
||||
//// return result;
|
||||
//// }
|
||||
//
|
||||
//
|
||||
// public SqlSessionFactory sqlSessionFactory(@Autowired DruidDataSource dataOneSource) throws Exception {
|
||||
// SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
|
||||
// sqlSessionFactoryBean.setDataSource(dataSource(dataOneSource));
|
||||
// return sqlSessionFactoryBean.getObject();
|
||||
// }
|
||||
//}
|
|
@ -0,0 +1,25 @@
|
|||
//package net.shapelight.common.config.shard;
|
||||
//
|
||||
//import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
|
||||
//import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
//import java.util.Collection;
|
||||
//
|
||||
///**
|
||||
// * 分表算法
|
||||
// */
|
||||
//public class TableOneAlg implements PreciseShardingAlgorithm<String> {
|
||||
//
|
||||
// private static Logger LOG = LoggerFactory.getLogger(TableOneAlg.class);
|
||||
//
|
||||
// /**
|
||||
// * 该表每个库分5张表
|
||||
// */
|
||||
// @Override
|
||||
// public String doSharding(Collection<String> names, PreciseShardingValue<String> value) {
|
||||
// LOG.debug("分表算法参数 {},{}",names,value);
|
||||
// int hash = HashUtil.rsHash(String.valueOf(value.getValue()));
|
||||
// return "ten+person_" + (hash % 5+1);
|
||||
// }
|
||||
//}
|
|
@ -0,0 +1,25 @@
|
|||
//package net.shapelight.common.config.shard;
|
||||
//
|
||||
//import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
|
||||
//import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
|
||||
//import org.slf4j.Logger;
|
||||
//import org.slf4j.LoggerFactory;
|
||||
//import java.util.Collection;
|
||||
//
|
||||
///**
|
||||
// * 分表算法
|
||||
// */
|
||||
//public class TableTwoAlg implements PreciseShardingAlgorithm<String> {
|
||||
//
|
||||
// private static Logger LOG = LoggerFactory.getLogger(TableTwoAlg.class);
|
||||
//
|
||||
// /**
|
||||
// * 该表每个库分5张表
|
||||
// */
|
||||
// @Override
|
||||
// public String doSharding(Collection<String> names, PreciseShardingValue<String> value) {
|
||||
// LOG.debug("分表算法参数 {},{}",names,value);
|
||||
// int hash = HashUtil.rsHash(String.valueOf(value.getValue()));
|
||||
// return "table_two_" + (hash % 5+1);
|
||||
// }
|
||||
//}
|
|
@ -0,0 +1,61 @@
|
|||
//package net.shapelight.common.config.sharding;
|
||||
//
|
||||
//import com.alibaba.druid.pool.DruidDataSource;
|
||||
//import com.google.common.collect.Maps;
|
||||
//import io.shardingjdbc.core.api.MasterSlaveDataSourceFactory;
|
||||
//import lombok.extern.slf4j.Slf4j;
|
||||
//import org.springframework.beans.factory.annotation.Autowired;
|
||||
//import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
//import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
//import org.springframework.context.annotation.Bean;
|
||||
//import org.springframework.context.annotation.Configuration;
|
||||
//
|
||||
//import javax.sql.DataSource;
|
||||
//import java.sql.SQLException;
|
||||
//import java.util.Map;
|
||||
//
|
||||
///**
|
||||
// * Created with Intellij IDEA.
|
||||
// * @author hjc
|
||||
// * @version 2018/5/8 0008
|
||||
// */
|
||||
//@Slf4j
|
||||
//@Configuration
|
||||
//@EnableConfigurationProperties(ShardingMasterSlaveConfig.class)
|
||||
//@ConditionalOnProperty({"sharding.jdbc.data-sources.ds_master.url", "sharding.jdbc.master-slave-rule.master-data-source-name"})
|
||||
//public class ShardingDataSourceConfig {
|
||||
//
|
||||
// @Autowired(required = false)
|
||||
// private ShardingMasterSlaveConfig shardingMasterSlaveConfig;
|
||||
//
|
||||
// @Bean("dataSource")
|
||||
// public DataSource masterSlaveDataSource() throws SQLException {
|
||||
// shardingMasterSlaveConfig.getDataSources().forEach((k, v) -> configDataSource(v));
|
||||
// Map<String, DataSource> dataSourceMap = Maps.newHashMap();
|
||||
// dataSourceMap.putAll(shardingMasterSlaveConfig.getDataSources());
|
||||
// DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, shardingMasterSlaveConfig.getMasterSlaveRule(), Maps.newHashMap());
|
||||
// log.info("masterSlaveDataSource config complete");
|
||||
// return dataSource;
|
||||
// }
|
||||
//
|
||||
// private void configDataSource(DruidDataSource druidDataSource) {
|
||||
// druidDataSource.setMaxActive(20);
|
||||
// druidDataSource.setInitialSize(1);
|
||||
// druidDataSource.setMaxWait(60000);
|
||||
// druidDataSource.setMinIdle(1);
|
||||
// druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
|
||||
// druidDataSource.setMinEvictableIdleTimeMillis(300000);
|
||||
// druidDataSource.setValidationQuery("select 'x'");
|
||||
// druidDataSource.setTestWhileIdle(true);
|
||||
// druidDataSource.setTestOnBorrow(false);
|
||||
// druidDataSource.setTestOnReturn(false);
|
||||
// druidDataSource.setPoolPreparedStatements(true);
|
||||
// druidDataSource.setMaxOpenPreparedStatements(20);
|
||||
// druidDataSource.setUseGlobalDataSourceStat(true);
|
||||
// try {
|
||||
// druidDataSource.setFilters("stat,wall,slf4j");
|
||||
// } catch (SQLException e) {
|
||||
// log.error("druid configuration initialization filter", e);
|
||||
// }
|
||||
// }
|
||||
//}
|
|
@ -0,0 +1,23 @@
|
|||
//package net.shapelight.common.config.sharding;
|
||||
//
|
||||
//import com.alibaba.druid.pool.DruidDataSource;
|
||||
//import io.shardingjdbc.core.api.config.MasterSlaveRuleConfiguration;
|
||||
//import lombok.Data;
|
||||
//import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
//
|
||||
//import java.util.HashMap;
|
||||
//import java.util.Map;
|
||||
//
|
||||
///**
|
||||
// * Created with Intellij IDEA.
|
||||
// * @author hjc
|
||||
// * @version 2018/5/8 0008
|
||||
// */
|
||||
//@Data
|
||||
//@ConfigurationProperties(prefix = "sharding.jdbc")
|
||||
//public class ShardingMasterSlaveConfig {
|
||||
//
|
||||
// private Map<String, DruidDataSource> dataSources = new HashMap<>();
|
||||
//
|
||||
// private MasterSlaveRuleConfiguration masterSlaveRule;
|
||||
//}
|
|
@ -0,0 +1,101 @@
|
|||
//package net.shapelight.common.config.shardingdangdang;
|
||||
//
|
||||
//
|
||||
//import com.alibaba.druid.pool.DruidDataSource;
|
||||
//import com.dangdang.ddframe.rdb.sharding.api.ShardingDataSourceFactory;
|
||||
//import com.dangdang.ddframe.rdb.sharding.api.rule.DataSourceRule;
|
||||
//import com.dangdang.ddframe.rdb.sharding.api.rule.ShardingRule;
|
||||
//import com.dangdang.ddframe.rdb.sharding.api.rule.TableRule;
|
||||
//import com.dangdang.ddframe.rdb.sharding.api.strategy.database.DatabaseShardingStrategy;
|
||||
//import com.dangdang.ddframe.rdb.sharding.api.strategy.table.TableShardingStrategy;
|
||||
//import com.mysql.jdbc.Driver;
|
||||
//import org.springframework.beans.factory.annotation.Autowired;
|
||||
//import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
//import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
//import org.springframework.context.annotation.Bean;
|
||||
//import org.springframework.context.annotation.Configuration;
|
||||
//import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
//import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
//import org.springframework.transaction.support.TransactionTemplate;
|
||||
//
|
||||
//import javax.sql.DataSource;
|
||||
//import java.sql.SQLException;
|
||||
//import java.util.Arrays;
|
||||
//import java.util.HashMap;
|
||||
//import java.util.Map;
|
||||
//
|
||||
//
|
||||
//@Configuration
|
||||
//@EnableTransactionManagement
|
||||
//@ConditionalOnClass(DruidDataSource.class)
|
||||
//@EnableConfigurationProperties(ShardDataSourceProperties.class)
|
||||
//public class ShardDataSourceConfig {
|
||||
// private final static String sys_db_bak = "sys_db_bak";
|
||||
// @Autowired
|
||||
// private ShardDataSourceProperties shardDataSourceProperties;
|
||||
//
|
||||
//
|
||||
// @Bean
|
||||
// public DataSource dataSource() throws SQLException {
|
||||
// return ShardingDataSourceFactory.createDataSource(shardingRule());
|
||||
// }
|
||||
//
|
||||
//
|
||||
// private DataSource ds() throws SQLException {
|
||||
// DruidDataSource ds = parentDs();
|
||||
// return ds;
|
||||
// }
|
||||
//
|
||||
// private DruidDataSource parentDs() throws SQLException {
|
||||
// DruidDataSource ds = new DruidDataSource();
|
||||
// ds.setDriverClassName(shardDataSourceProperties.getDriverClassName());
|
||||
// ds.setUrl(shardDataSourceProperties.getUrl());
|
||||
// ds.setUsername(shardDataSourceProperties.getUsername());
|
||||
// ds.setPassword(shardDataSourceProperties.getPassword());
|
||||
// ds.setFilters(shardDataSourceProperties.getFilters());
|
||||
// ds.setMaxActive(shardDataSourceProperties.getMaxActive());
|
||||
// ds.setInitialSize(shardDataSourceProperties.getInitialSize());
|
||||
// ds.setMaxWait(shardDataSourceProperties.getMaxWait());
|
||||
// ds.setMinIdle(shardDataSourceProperties.getMinIdle());
|
||||
// ds.setTimeBetweenEvictionRunsMillis(shardDataSourceProperties.getTimeBetweenEvictionRunsMillis());
|
||||
// ds.setMinEvictableIdleTimeMillis(shardDataSourceProperties.getMinEvictableIdleTimeMillis());
|
||||
// ds.setValidationQuery(shardDataSourceProperties.getValidationQuery());
|
||||
// ds.setTestWhileIdle(shardDataSourceProperties.isTestWhileIdle());
|
||||
// ds.setTestOnBorrow(shardDataSourceProperties.isTestOnBorrow());
|
||||
// ds.setTestOnReturn(shardDataSourceProperties.isTestOnReturn());
|
||||
// ds.setPoolPreparedStatements(shardDataSourceProperties.isPoolPreparedStatements());
|
||||
// ds.setMaxPoolPreparedStatementPerConnectionSize(
|
||||
// shardDataSourceProperties.getMaxPoolPreparedStatementPerConnectionSize());
|
||||
// ds.setRemoveAbandoned(shardDataSourceProperties.isRemoveAbandoned());
|
||||
// ds.setRemoveAbandonedTimeout(shardDataSourceProperties.getRemoveAbandonedTimeout());
|
||||
// ds.setLogAbandoned(shardDataSourceProperties.isLogAbandoned());
|
||||
// ds.setConnectionInitSqls(shardDataSourceProperties.getConnectionInitSqls());
|
||||
// ds.setConnectionProperties(shardDataSourceProperties.getConnectionProperties());
|
||||
// return ds;
|
||||
// }
|
||||
//
|
||||
// private DataSourceRule getDataSourceRule() throws SQLException {
|
||||
// Map<String, DataSource> dataSourceMap = new HashMap<>(2);
|
||||
// dataSourceMap.put("ds", ds());
|
||||
// DataSourceRule dataSourceRule = new DataSourceRule(dataSourceMap);
|
||||
// return dataSourceRule;
|
||||
// }
|
||||
//
|
||||
// private TableRule getOrderTableRule() throws SQLException {
|
||||
// //我就建了两张表order_0和order_1,如有需要可以调整数组大小
|
||||
// String[] uns = new String[2];
|
||||
// for (int i = 0; i < 2; i++) {
|
||||
// uns[i] = sys_db_bak.concat("_").concat(String.valueOf(i));
|
||||
// }
|
||||
//// for (int i = 10; i <= 99; i++) {
|
||||
//// uns[i] = order.concat("_").concat(String.valueOf(i));
|
||||
//// }
|
||||
// TableRule tableRule = TableRule.builder(sys_db_bak).actualTables(Arrays.asList(uns)).dataSourceRule(getDataSourceRule()).tableShardingStrategy(new TableShardingStrategy("id", new UserIdShardingAlgorithm())).build();
|
||||
// return tableRule;
|
||||
// }
|
||||
//
|
||||
// private ShardingRule shardingRule() throws SQLException {
|
||||
// ShardingRule shardingRule = ShardingRule.builder().dataSourceRule(getDataSourceRule()).tableRules(Arrays.asList(getOrderTableRule())).build();
|
||||
// return shardingRule;
|
||||
// }
|
||||
//}
|
|
@ -0,0 +1,207 @@
|
|||
//package net.shapelight.common.config.shardingdangdang;
|
||||
//
|
||||
//import java.util.List;
|
||||
//
|
||||
//import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
//
|
||||
//@ConfigurationProperties(prefix = "sharding.jdbc")
|
||||
//public class ShardDataSourceProperties {
|
||||
// private String driverClassName;
|
||||
// private String url;
|
||||
// private String username;
|
||||
// private String password;
|
||||
// private String filters;
|
||||
// private int maxActive;
|
||||
// private int initialSize;
|
||||
// private int maxWait;
|
||||
// private int minIdle;
|
||||
// private int timeBetweenEvictionRunsMillis;
|
||||
// private int minEvictableIdleTimeMillis;
|
||||
// private String validationQuery;
|
||||
// private boolean testWhileIdle;
|
||||
// private boolean testOnBorrow;
|
||||
// private boolean testOnReturn;
|
||||
// private boolean poolPreparedStatements;
|
||||
// private int maxPoolPreparedStatementPerConnectionSize;
|
||||
// private boolean removeAbandoned;
|
||||
// private int removeAbandonedTimeout;
|
||||
// private boolean logAbandoned;
|
||||
// private List<String> connectionInitSqls;
|
||||
// private String connectionProperties;
|
||||
//
|
||||
// public String getDriverClassName() {
|
||||
// return driverClassName;
|
||||
// }
|
||||
//
|
||||
// public void setDriverClassName(String driverClassName) {
|
||||
// this.driverClassName = driverClassName;
|
||||
// }
|
||||
//
|
||||
// public String getUrl() {
|
||||
// return url;
|
||||
// }
|
||||
//
|
||||
// public void setUrl(String url) {
|
||||
// this.url = url;
|
||||
// }
|
||||
//
|
||||
// public String getUsername() {
|
||||
// return username;
|
||||
// }
|
||||
//
|
||||
// public void setUsername(String username) {
|
||||
// this.username = username;
|
||||
// }
|
||||
//
|
||||
// public String getPassword() {
|
||||
// return password;
|
||||
// }
|
||||
//
|
||||
// public void setPassword(String password) {
|
||||
// this.password = password;
|
||||
// }
|
||||
//
|
||||
// public String getFilters() {
|
||||
// return filters;
|
||||
// }
|
||||
//
|
||||
// public void setFilters(String filters) {
|
||||
// this.filters = filters;
|
||||
// }
|
||||
//
|
||||
// public int getMaxActive() {
|
||||
// return maxActive;
|
||||
// }
|
||||
//
|
||||
// public void setMaxActive(int maxActive) {
|
||||
// this.maxActive = maxActive;
|
||||
// }
|
||||
//
|
||||
// public int getInitialSize() {
|
||||
// return initialSize;
|
||||
// }
|
||||
//
|
||||
// public void setInitialSize(int initialSize) {
|
||||
// this.initialSize = initialSize;
|
||||
// }
|
||||
//
|
||||
// public int getMaxWait() {
|
||||
// return maxWait;
|
||||
// }
|
||||
//
|
||||
// public void setMaxWait(int maxWait) {
|
||||
// this.maxWait = maxWait;
|
||||
// }
|
||||
//
|
||||
// public int getMinIdle() {
|
||||
// return minIdle;
|
||||
// }
|
||||
//
|
||||
// public void setMinIdle(int minIdle) {
|
||||
// this.minIdle = minIdle;
|
||||
// }
|
||||
//
|
||||
// public int getTimeBetweenEvictionRunsMillis() {
|
||||
// return timeBetweenEvictionRunsMillis;
|
||||
// }
|
||||
//
|
||||
// public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
|
||||
// this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
|
||||
// }
|
||||
//
|
||||
// public int getMinEvictableIdleTimeMillis() {
|
||||
// return minEvictableIdleTimeMillis;
|
||||
// }
|
||||
//
|
||||
// public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
|
||||
// this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
|
||||
// }
|
||||
//
|
||||
// public String getValidationQuery() {
|
||||
// return validationQuery;
|
||||
// }
|
||||
//
|
||||
// public void setValidationQuery(String validationQuery) {
|
||||
// this.validationQuery = validationQuery;
|
||||
// }
|
||||
//
|
||||
// public boolean isTestWhileIdle() {
|
||||
// return testWhileIdle;
|
||||
// }
|
||||
//
|
||||
// public void setTestWhileIdle(boolean testWhileIdle) {
|
||||
// this.testWhileIdle = testWhileIdle;
|
||||
// }
|
||||
//
|
||||
// public boolean isTestOnBorrow() {
|
||||
// return testOnBorrow;
|
||||
// }
|
||||
//
|
||||
// public void setTestOnBorrow(boolean testOnBorrow) {
|
||||
// this.testOnBorrow = testOnBorrow;
|
||||
// }
|
||||
//
|
||||
// public boolean isTestOnReturn() {
|
||||
// return testOnReturn;
|
||||
// }
|
||||
//
|
||||
// public void setTestOnReturn(boolean testOnReturn) {
|
||||
// this.testOnReturn = testOnReturn;
|
||||
// }
|
||||
//
|
||||
// public boolean isPoolPreparedStatements() {
|
||||
// return poolPreparedStatements;
|
||||
// }
|
||||
//
|
||||
// public void setPoolPreparedStatements(boolean poolPreparedStatements) {
|
||||
// this.poolPreparedStatements = poolPreparedStatements;
|
||||
// }
|
||||
//
|
||||
// public int getMaxPoolPreparedStatementPerConnectionSize() {
|
||||
// return maxPoolPreparedStatementPerConnectionSize;
|
||||
// }
|
||||
//
|
||||
// public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
|
||||
// this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
|
||||
// }
|
||||
//
|
||||
// public boolean isRemoveAbandoned() {
|
||||
// return removeAbandoned;
|
||||
// }
|
||||
//
|
||||
// public void setRemoveAbandoned(boolean removeAbandoned) {
|
||||
// this.removeAbandoned = removeAbandoned;
|
||||
// }
|
||||
//
|
||||
// public int getRemoveAbandonedTimeout() {
|
||||
// return removeAbandonedTimeout;
|
||||
// }
|
||||
//
|
||||
// public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) {
|
||||
// this.removeAbandonedTimeout = removeAbandonedTimeout;
|
||||
// }
|
||||
//
|
||||
// public boolean isLogAbandoned() {
|
||||
// return logAbandoned;
|
||||
// }
|
||||
//
|
||||
// public void setLogAbandoned(boolean logAbandoned) {
|
||||
// this.logAbandoned = logAbandoned;
|
||||
// }
|
||||
//
|
||||
// public List<String> getConnectionInitSqls() {
|
||||
// return connectionInitSqls;
|
||||
// }
|
||||
//
|
||||
// public void setConnectionInitSqls(List<String> connectionInitSqls) {
|
||||
// this.connectionInitSqls = connectionInitSqls;
|
||||
// }
|
||||
//
|
||||
// public String getConnectionProperties() {
|
||||
// return connectionProperties;
|
||||
// }
|
||||
//
|
||||
// public void setConnectionProperties(String connectionProperties) {
|
||||
// this.connectionProperties = connectionProperties;
|
||||
// }
|
||||
//}
|
|
@ -0,0 +1,55 @@
|
|||
//package net.shapelight.common.config.shardingdangdang;
|
||||
//
|
||||
//
|
||||
//import java.util.Collection;
|
||||
//import java.util.LinkedHashSet;
|
||||
//
|
||||
//import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
|
||||
//import com.dangdang.ddframe.rdb.sharding.api.strategy.table.SingleKeyTableShardingAlgorithm;
|
||||
//
|
||||
//import com.google.common.collect.Range;
|
||||
//
|
||||
///**
|
||||
// *
|
||||
// */
|
||||
//public class UserIdShardingAlgorithm implements SingleKeyTableShardingAlgorithm<Integer> {
|
||||
//
|
||||
// @Override
|
||||
// public String doEqualSharding(Collection<String> tableNames, ShardingValue<Integer> shardingValue) {
|
||||
// for (String each : tableNames) {
|
||||
// if (each.endsWith(shardingValue.getValue()%2+"")) {
|
||||
// return each;
|
||||
// }
|
||||
// }
|
||||
// throw new IllegalArgumentException();
|
||||
// }
|
||||
//
|
||||
//
|
||||
// @Override
|
||||
// public Collection<String> doInSharding(Collection<String> tableNames, ShardingValue<Integer> shardingValue) {
|
||||
// Collection<String> result = new LinkedHashSet<>(tableNames.size());
|
||||
// for (Integer value : shardingValue.getValues()) {
|
||||
// for (String tableName : tableNames) {
|
||||
// if (tableName.endsWith(value%2+"")) {
|
||||
// result.add(tableName);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return result;
|
||||
// }
|
||||
//
|
||||
//
|
||||
// @Override
|
||||
// public Collection<String> doBetweenSharding(Collection<String> tableNames, ShardingValue<Integer> shardingValue) {
|
||||
// Collection<String> result = new LinkedHashSet<>(tableNames.size());
|
||||
// Range<Integer> range = shardingValue.getValueRange();
|
||||
// for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) {
|
||||
// for (String each : tableNames) {
|
||||
// if (each.endsWith(i%2+"")) {
|
||||
// result.add(each);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return result;
|
||||
// }
|
||||
//}
|
|
@ -0,0 +1,51 @@
|
|||
|
||||
|
||||
package net.shapelight.common.exception;
|
||||
|
||||
import net.shapelight.common.utils.R;
|
||||
import org.apache.shiro.authz.AuthorizationException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
/**
|
||||
* 异常处理器
|
||||
*
|
||||
*
|
||||
*/
|
||||
@RestControllerAdvice
|
||||
public class RRExceptionHandler {
|
||||
private Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
/**
|
||||
* 处理自定义异常
|
||||
*/
|
||||
@ExceptionHandler(RRException.class)
|
||||
public R handleRRException(RRException e){
|
||||
R r = new R();
|
||||
r.put("code", e.getCode());
|
||||
r.put("msg", e.getMessage());
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
@ExceptionHandler(DuplicateKeyException.class)
|
||||
public R handleDuplicateKeyException(DuplicateKeyException e){
|
||||
logger.error(e.getMessage(), e);
|
||||
return R.error("数据库中已存在该记录");
|
||||
}
|
||||
|
||||
@ExceptionHandler(AuthorizationException.class)
|
||||
public R handleAuthorizationException(AuthorizationException e){
|
||||
logger.error(e.getMessage(), e);
|
||||
return R.error("没有权限,请联系管理员授权");
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public R handleException(Exception e){
|
||||
logger.error(e.getMessage(), e);
|
||||
return R.error();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package net.shapelight.common.handler;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 按自定义字段参数,组成动态表名
|
||||
*/
|
||||
public class CustomizeTableNameHandler implements TableNameHandler {
|
||||
//用于记录哪些表可以使用该月份动态表名处理器(即哪些表可以分表)
|
||||
private List<String> tableNames;
|
||||
|
||||
//构造函数,构造动态表名处理器的时候,传递tableNames参数
|
||||
public CustomizeTableNameHandler(String ...tableNames) {
|
||||
this.tableNames = Arrays.asList(tableNames);
|
||||
}
|
||||
|
||||
//每个请求线程维护一个分表字段数据,避免多线程数据冲突。所以使用ThreadLocal
|
||||
private static final ThreadLocal<String> CELL_DATA = new ThreadLocal<>();
|
||||
|
||||
//设置请求线程的month数据
|
||||
public static void setData(String month) {
|
||||
CELL_DATA.set(month);
|
||||
}
|
||||
|
||||
//删除当前请求线程的month数据
|
||||
public static void removeData() {
|
||||
CELL_DATA.remove();
|
||||
}
|
||||
|
||||
//动态表名接口实现方法
|
||||
@Override
|
||||
public String dynamicTableName(String sql, String tableName) {
|
||||
if (this.tableNames.contains(tableName)){
|
||||
return tableName + "_" + CELL_DATA.get(); //表名增加分表字段后缀
|
||||
}else{
|
||||
return tableName; //表名原样返回
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package net.shapelight.common.handler;
|
||||
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class TimeHandler implements MetaObjectHandler {
|
||||
/* @Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
this.setFieldValByName("createTime", new Date(), metaObject);
|
||||
this.setFieldValByName("updateTime", new Date(), metaObject);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
this.setFieldValByName("updateTime", new Date(), metaObject);
|
||||
}*/
|
||||
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
|
||||
this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
|
||||
this.strictInsertFill(metaObject, "deleteFlag", Integer.class, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package net.shapelight.common.swaggermap;
|
||||
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface ApiJsonObject {
|
||||
|
||||
ApiJsonProperty[] value(); //对象属性值
|
||||
|
||||
String name(); //对象名称
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
package net.shapelight.common.swaggermap;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.ANNOTATION_TYPE)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface ApiJsonProperty {
|
||||
|
||||
String key(); //key
|
||||
|
||||
String example() default "";
|
||||
|
||||
String type() default "string"; //支持string 和 int
|
||||
|
||||
String description() default "";
|
||||
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
package net.shapelight.common.swaggermap;
|
||||
|
||||
|
||||
import com.fasterxml.classmate.TypeResolver;
|
||||
import com.google.common.base.Optional;
|
||||
import javassist.*;
|
||||
import javassist.bytecode.AnnotationsAttribute;
|
||||
import javassist.bytecode.ConstPool;
|
||||
import javassist.bytecode.annotation.Annotation;
|
||||
import javassist.bytecode.annotation.IntegerMemberValue;
|
||||
import javassist.bytecode.annotation.StringMemberValue;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import springfox.documentation.schema.ModelRef;
|
||||
import springfox.documentation.service.ResolvedMethodParameter;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spi.service.ParameterBuilderPlugin;
|
||||
import springfox.documentation.spi.service.contexts.ParameterContext;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
@Order //plugin加载顺序,默认是最后加载
|
||||
public class MapApiReader implements ParameterBuilderPlugin {
|
||||
@Autowired
|
||||
private TypeResolver typeResolver;
|
||||
|
||||
@Override
|
||||
public void apply(ParameterContext parameterContext) {
|
||||
ResolvedMethodParameter methodParameter = parameterContext.resolvedMethodParameter();
|
||||
|
||||
if (methodParameter.getParameterType().canCreateSubtype(Map.class) || methodParameter.getParameterType().canCreateSubtype(String.class)) { //判断是否需要修改对象ModelRef,这里我判断的是Map类型和String类型需要重新修改ModelRef对象
|
||||
Optional<ApiJsonObject> optional = methodParameter.findAnnotation(ApiJsonObject.class); //根据参数上的ApiJsonObject注解中的参数动态生成Class
|
||||
if (optional.isPresent()) {
|
||||
String name = optional.get().name(); //model 名称
|
||||
ApiJsonProperty[] properties = optional.get().value();
|
||||
|
||||
parameterContext.getDocumentationContext().getAdditionalModels().add(typeResolver.resolve(createRefModel(properties, name))); //像documentContext的Models中添加我们新生成的Class
|
||||
|
||||
parameterContext.parameterBuilder() //修改Map参数的ModelRef为我们动态生成的class
|
||||
.parameterType("body")
|
||||
.modelRef(new ModelRef(name))
|
||||
.name(name);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private final static String basePackage = "net.shapelight.in.swagger.model."; //动态生成的Class名
|
||||
|
||||
/**
|
||||
* 根据propertys中的值动态生成含有Swagger注解的javaBeen
|
||||
*/
|
||||
private Class createRefModel(ApiJsonProperty[] propertys, String name) {
|
||||
ClassPool pool = ClassPool.getDefault();
|
||||
CtClass ctClass = pool.makeClass(basePackage + name);
|
||||
|
||||
try {
|
||||
for (ApiJsonProperty property : propertys) {
|
||||
ctClass.addField(createField(property, ctClass));
|
||||
}
|
||||
return ctClass.toClass();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据property的值生成含有swagger apiModelProperty注解的属性
|
||||
*/
|
||||
private CtField createField(ApiJsonProperty property, CtClass ctClass) throws NotFoundException, CannotCompileException {
|
||||
CtField ctField = new CtField(getFieldType(property.type()), property.key(), ctClass);
|
||||
ctField.setModifiers(Modifier.PUBLIC);
|
||||
|
||||
ConstPool constPool = ctClass.getClassFile().getConstPool();
|
||||
|
||||
AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
|
||||
Annotation ann = new Annotation("io.swagger.annotations.ApiModelProperty", constPool);
|
||||
ann.addMemberValue("value", new StringMemberValue(property.description(), constPool));
|
||||
if (ctField.getType().subclassOf(ClassPool.getDefault().get(String.class.getName())))
|
||||
ann.addMemberValue("example", new StringMemberValue(property.example(), constPool));
|
||||
if (ctField.getType().subclassOf(ClassPool.getDefault().get(Integer.class.getName())))
|
||||
ann.addMemberValue("example", new IntegerMemberValue(Integer.parseInt(property.example()), constPool));
|
||||
|
||||
attr.addAnnotation(ann);
|
||||
ctField.getFieldInfo().addAttribute(attr);
|
||||
|
||||
return ctField;
|
||||
}
|
||||
|
||||
private CtClass getFieldType(String type) throws NotFoundException {
|
||||
CtClass fileType = null;
|
||||
switch (type) {
|
||||
case "string":
|
||||
fileType = ClassPool.getDefault().get(String.class.getName());
|
||||
break;
|
||||
case "int":
|
||||
fileType = ClassPool.getDefault().get(Integer.class.getName());
|
||||
break;
|
||||
}
|
||||
return fileType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(DocumentationType delimiter) {
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.db.PageResult;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
|
||||
public class BeanUtils {
|
||||
|
||||
public static <T> T toBean(Object source, Class<T> targetClass) {
|
||||
return BeanUtil.toBean(source, targetClass);
|
||||
}
|
||||
|
||||
public static <T> T toBean(Object source, Class<T> targetClass, Consumer<T> peek) {
|
||||
T target = toBean(source, targetClass);
|
||||
if (target != null) {
|
||||
peek.accept(target);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
public static <S, T> List<T> toBean(List<S> source, Class<T> targetType) {
|
||||
if (source == null) {
|
||||
return null;
|
||||
}
|
||||
return CollectionUtils.convertList(source, s -> toBean(s, targetType));
|
||||
}
|
||||
|
||||
public static <S, T> List<T> toBean(List<S> source, Class<T> targetType, Consumer<T> peek) {
|
||||
List<T> list = toBean(source, targetType);
|
||||
if (list != null) {
|
||||
list.forEach(peek);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,326 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
|
||||
|
||||
public class CollectionUtils {
|
||||
|
||||
public static boolean containsAny(Object source, Object... targets) {
|
||||
return asList(targets).contains(source);
|
||||
}
|
||||
|
||||
public static boolean isAnyEmpty(Collection<?>... collections) {
|
||||
return Arrays.stream(collections).anyMatch(CollectionUtil::isEmpty);
|
||||
}
|
||||
|
||||
public static <T> boolean anyMatch(Collection<T> from, Predicate<T> predicate) {
|
||||
return from.stream().anyMatch(predicate);
|
||||
}
|
||||
|
||||
public static <T> List<T> filterList(Collection<T> from, Predicate<T> predicate) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return from.stream().filter(predicate).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static <T, R> List<T> distinct(Collection<T> from, Function<T, R> keyMapper) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return distinct(from, keyMapper, (t1, t2) -> t1);
|
||||
}
|
||||
|
||||
public static <T, R> List<T> distinct(Collection<T> from, Function<T, R> keyMapper, BinaryOperator<T> cover) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return new ArrayList<>(convertMap(from, keyMapper, Function.identity(), cover).values());
|
||||
}
|
||||
|
||||
public static <T, U> List<U> convertList(T[] from, Function<T, U> func) {
|
||||
if (ArrayUtil.isEmpty(from)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return convertList(Arrays.asList(from), func);
|
||||
}
|
||||
|
||||
public static <T, U> List<U> convertList(Collection<T> from, Function<T, U> func) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return from.stream().map(func).filter(Objects::nonNull).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static <T, U> List<U> convertList(Collection<T> from, Function<T, U> func, Predicate<T> filter) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return from.stream().filter(filter).map(func).filter(Objects::nonNull).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static <T, U> List<U> convertListByFlatMap(Collection<T> from,
|
||||
Function<T, ? extends Stream<? extends U>> func) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return from.stream().filter(Objects::nonNull).flatMap(func).filter(Objects::nonNull).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static <T, U, R> List<R> convertListByFlatMap(Collection<T> from,
|
||||
Function<? super T, ? extends U> mapper,
|
||||
Function<U, ? extends Stream<? extends R>> func) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return from.stream().map(mapper).filter(Objects::nonNull).flatMap(func).filter(Objects::nonNull).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static <K, V> List<V> mergeValuesFromMap(Map<K, List<V>> map) {
|
||||
return map.values()
|
||||
.stream()
|
||||
.flatMap(List::stream)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static <T> Set<T> convertSet(Collection<T> from) {
|
||||
return convertSet(from, v -> v);
|
||||
}
|
||||
|
||||
public static <T, U> Set<U> convertSet(Collection<T> from, Function<T, U> func) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new HashSet<>();
|
||||
}
|
||||
return from.stream().map(func).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public static <T, U> Set<U> convertSet(Collection<T> from, Function<T, U> func, Predicate<T> filter) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new HashSet<>();
|
||||
}
|
||||
return from.stream().filter(filter).map(func).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public static <T, K> Map<K, T> convertMapByFilter(Collection<T> from, Predicate<T> filter, Function<T, K> keyFunc) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return from.stream().filter(filter).collect(Collectors.toMap(keyFunc, v -> v));
|
||||
}
|
||||
|
||||
public static <T, U> Set<U> convertSetByFlatMap(Collection<T> from,
|
||||
Function<T, ? extends Stream<? extends U>> func) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new HashSet<>();
|
||||
}
|
||||
return from.stream().filter(Objects::nonNull).flatMap(func).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public static <T, U, R> Set<R> convertSetByFlatMap(Collection<T> from,
|
||||
Function<? super T, ? extends U> mapper,
|
||||
Function<U, ? extends Stream<? extends R>> func) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new HashSet<>();
|
||||
}
|
||||
return from.stream().map(mapper).filter(Objects::nonNull).flatMap(func).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public static <T, K> Map<K, T> convertMap(Collection<T> from, Function<T, K> keyFunc) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return convertMap(from, keyFunc, Function.identity());
|
||||
}
|
||||
|
||||
public static <T, K> Map<K, T> convertMap(Collection<T> from, Function<T, K> keyFunc, Supplier<? extends Map<K, T>> supplier) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return supplier.get();
|
||||
}
|
||||
return convertMap(from, keyFunc, Function.identity(), supplier);
|
||||
}
|
||||
|
||||
public static <T, K, V> Map<K, V> convertMap(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return convertMap(from, keyFunc, valueFunc, (v1, v2) -> v1);
|
||||
}
|
||||
|
||||
public static <T, K, V> Map<K, V> convertMap(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc, BinaryOperator<V> mergeFunction) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return convertMap(from, keyFunc, valueFunc, mergeFunction, HashMap::new);
|
||||
}
|
||||
|
||||
public static <T, K, V> Map<K, V> convertMap(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc, Supplier<? extends Map<K, V>> supplier) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return supplier.get();
|
||||
}
|
||||
return convertMap(from, keyFunc, valueFunc, (v1, v2) -> v1, supplier);
|
||||
}
|
||||
|
||||
public static <T, K, V> Map<K, V> convertMap(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc, BinaryOperator<V> mergeFunction, Supplier<? extends Map<K, V>> supplier) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return from.stream().collect(Collectors.toMap(keyFunc, valueFunc, mergeFunction, supplier));
|
||||
}
|
||||
|
||||
public static <T, K> Map<K, List<T>> convertMultiMap(Collection<T> from, Function<T, K> keyFunc) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return from.stream().collect(Collectors.groupingBy(keyFunc, Collectors.mapping(t -> t, Collectors.toList())));
|
||||
}
|
||||
|
||||
public static <T, K, V> Map<K, List<V>> convertMultiMap(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return from.stream()
|
||||
.collect(Collectors.groupingBy(keyFunc, Collectors.mapping(valueFunc, Collectors.toList())));
|
||||
}
|
||||
|
||||
// 暂时没想好名字,先以 2 结尾噶
|
||||
public static <T, K, V> Map<K, Set<V>> convertMultiMap2(Collection<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return new HashMap<>();
|
||||
}
|
||||
return from.stream().collect(Collectors.groupingBy(keyFunc, Collectors.mapping(valueFunc, Collectors.toSet())));
|
||||
}
|
||||
|
||||
public static <T, K> Map<K, T> convertImmutableMap(Collection<T> from, Function<T, K> keyFunc) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
ImmutableMap.Builder<K, T> builder = ImmutableMap.builder();
|
||||
from.forEach(item -> builder.put(keyFunc.apply(item), item));
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对比老、新两个列表,找出新增、修改、删除的数据
|
||||
*
|
||||
* @param oldList 老列表
|
||||
* @param newList 新列表
|
||||
* @param sameFunc 对比函数,返回 true 表示相同,返回 false 表示不同
|
||||
* 注意,same 是通过每个元素的“标识”,判断它们是不是同一个数据
|
||||
* @return [新增列表、修改列表、删除列表]
|
||||
*/
|
||||
public static <T> List<List<T>> diffList(Collection<T> oldList, Collection<T> newList,
|
||||
BiFunction<T, T, Boolean> sameFunc) {
|
||||
List<T> createList = new LinkedList<>(newList); // 默认都认为是新增的,后续会进行移除
|
||||
List<T> updateList = new ArrayList<>();
|
||||
List<T> deleteList = new ArrayList<>();
|
||||
|
||||
// 通过以 oldList 为主遍历,找出 updateList 和 deleteList
|
||||
for (T oldObj : oldList) {
|
||||
// 1. 寻找是否有匹配的
|
||||
T foundObj = null;
|
||||
for (Iterator<T> iterator = createList.iterator(); iterator.hasNext(); ) {
|
||||
T newObj = iterator.next();
|
||||
// 1.1 不匹配,则直接跳过
|
||||
if (!sameFunc.apply(oldObj, newObj)) {
|
||||
continue;
|
||||
}
|
||||
// 1.2 匹配,则移除,并结束寻找
|
||||
iterator.remove();
|
||||
foundObj = newObj;
|
||||
break;
|
||||
}
|
||||
// 2. 匹配添加到 updateList;不匹配则添加到 deleteList 中
|
||||
if (foundObj != null) {
|
||||
updateList.add(foundObj);
|
||||
} else {
|
||||
deleteList.add(oldObj);
|
||||
}
|
||||
}
|
||||
return asList(createList, updateList, deleteList);
|
||||
}
|
||||
|
||||
public static boolean containsAny(Collection<?> source, Collection<?> candidates) {
|
||||
return org.springframework.util.CollectionUtils.containsAny(source, candidates);
|
||||
}
|
||||
|
||||
public static <T> T getFirst(List<T> from) {
|
||||
return !CollectionUtil.isEmpty(from) ? from.get(0) : null;
|
||||
}
|
||||
|
||||
public static <T> T findFirst(Collection<T> from, Predicate<T> predicate) {
|
||||
return findFirst(from, predicate, Function.identity());
|
||||
}
|
||||
|
||||
public static <T, U> U findFirst(Collection<T> from, Predicate<T> predicate, Function<T, U> func) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return null;
|
||||
}
|
||||
return from.stream().filter(predicate).findFirst().map(func).orElse(null);
|
||||
}
|
||||
|
||||
public static <T, V extends Comparable<? super V>> V getMaxValue(Collection<T> from, Function<T, V> valueFunc) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return null;
|
||||
}
|
||||
assert !from.isEmpty(); // 断言,避免告警
|
||||
T t = from.stream().max(Comparator.comparing(valueFunc)).get();
|
||||
return valueFunc.apply(t);
|
||||
}
|
||||
|
||||
public static <T, V extends Comparable<? super V>> V getMinValue(List<T> from, Function<T, V> valueFunc) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return null;
|
||||
}
|
||||
assert from.size() > 0; // 断言,避免告警
|
||||
T t = from.stream().min(Comparator.comparing(valueFunc)).get();
|
||||
return valueFunc.apply(t);
|
||||
}
|
||||
|
||||
public static <T, V extends Comparable<? super V>> T getMinObject(List<T> from, Function<T, V> valueFunc) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return null;
|
||||
}
|
||||
assert from.size() > 0; // 断言,避免告警
|
||||
return from.stream().min(Comparator.comparing(valueFunc)).get();
|
||||
}
|
||||
|
||||
public static <T, V extends Comparable<? super V>> V getSumValue(Collection<T> from, Function<T, V> valueFunc,
|
||||
BinaryOperator<V> accumulator) {
|
||||
return getSumValue(from, valueFunc, accumulator, null);
|
||||
}
|
||||
|
||||
public static <T, V extends Comparable<? super V>> V getSumValue(Collection<T> from, Function<T, V> valueFunc,
|
||||
BinaryOperator<V> accumulator, V defaultValue) {
|
||||
if (CollUtil.isEmpty(from)) {
|
||||
return defaultValue;
|
||||
}
|
||||
assert !from.isEmpty(); // 断言,避免告警
|
||||
return from.stream().map(valueFunc).filter(Objects::nonNull).reduce(accumulator).orElse(defaultValue);
|
||||
}
|
||||
|
||||
public static <T> void addIfNotNull(Collection<T> coll, T item) {
|
||||
if (item == null) {
|
||||
return;
|
||||
}
|
||||
coll.add(item);
|
||||
}
|
||||
|
||||
public static <T> Collection<T> singleton(T obj) {
|
||||
return obj == null ? Collections.emptyList() : Collections.singleton(obj);
|
||||
}
|
||||
|
||||
public static <T> List<T> newArrayList(List<List<T>> list) {
|
||||
return list.stream().flatMap(Collection::stream).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,230 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.tools.zip.ZipEntry;
|
||||
import org.apache.tools.zip.ZipFile;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.*;
|
||||
|
||||
public class CompressZipUtils {
|
||||
// @Autowired
|
||||
// private static List<String> copyFileNames = new ArrayList<>();
|
||||
private static List<String> excelFiles = new ArrayList<>();
|
||||
private static List<String> imageFiles = new ArrayList<>();
|
||||
|
||||
public static List<String> getExcelFiles() {
|
||||
return excelFiles;
|
||||
}
|
||||
|
||||
public static List<String> getImageFiles() {
|
||||
return imageFiles;
|
||||
}
|
||||
// /*
|
||||
// 解压到指定文件夹下,然后拷贝到目标文件夹下覆盖
|
||||
// */
|
||||
// @SuppressWarnings("rawtypes")
|
||||
// public static void unZipFiles(File zipFile, String unZipDir,String descDir) throws Exception {
|
||||
// File pathFile = new File(unZipDir);
|
||||
// if(!pathFile.exists()){
|
||||
// pathFile.mkdirs();
|
||||
// }
|
||||
// ZipFile zip = new ZipFile(zipFile);
|
||||
// //List<String> fileNames = new ArrayList<>();
|
||||
// for(Enumeration entries = zip.getEntries();entries.hasMoreElements();){
|
||||
// ZipEntry entry = (ZipEntry)entries.nextElement();
|
||||
// entry.setUnixMode(644); // 解决linux乱码
|
||||
// String zipEntryName = entry.getName();
|
||||
// InputStream in = zip.getInputStream(entry);
|
||||
// String outPath = (unZipDir+zipEntryName).replaceAll("\\*", "/");;
|
||||
// //判断路径是否存在,不存在则创建文件路径
|
||||
// File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
|
||||
// if(!file.exists()){
|
||||
// file.mkdirs();
|
||||
// }
|
||||
// //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
|
||||
// if(new File(outPath).isDirectory()){
|
||||
// continue;
|
||||
// }
|
||||
// //输出文件路径信息
|
||||
// //System.out.println(outPath);
|
||||
//
|
||||
// OutputStream out = new FileOutputStream(outPath);
|
||||
// byte[] buf1 = new byte[1024];
|
||||
// int len;
|
||||
// while((len=in.read(buf1))>0){
|
||||
// out.write(buf1,0,len);
|
||||
// }
|
||||
// in.close();
|
||||
// out.close();
|
||||
// //fileNames.add(zipEntryName);
|
||||
// }
|
||||
// zip.close();
|
||||
//
|
||||
//// String[] smailFace = getSmallFaceFiles("D:\\images");
|
||||
//// System.out.println("******************解压完毕********************");
|
||||
//// System.out.println("******************拷贝文件********************");
|
||||
// File unZipDirFile = new File(unZipDir);
|
||||
// List<String> fileNames = copyJpgFiles(unZipDirFile,descDir);
|
||||
//// System.out.println("******************删除小图片********************");
|
||||
// //int c = deleteSmailFace(fileNames,smallDir);
|
||||
// //System.out.println("******************删除压缩包********************");
|
||||
// zipFile.delete();
|
||||
// FileUtils.deleteDirectory(unZipDirFile);
|
||||
// }
|
||||
|
||||
|
||||
/*
|
||||
解压到指定文件夹下,然后拷贝到目标文件夹下覆盖
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static Map<String,List<String>> unZipFiles(File zipFile, String unZipDir) throws Exception {
|
||||
excelFiles.clear();
|
||||
imageFiles.clear();
|
||||
Map<String,List<String>> filesMap = new HashMap<>();
|
||||
File pathFile = new File(unZipDir);
|
||||
if(!pathFile.exists()){
|
||||
pathFile.mkdirs();
|
||||
}
|
||||
ZipFile zip = new ZipFile(zipFile);
|
||||
//List<String> fileNames = new ArrayList<>();
|
||||
for(Enumeration entries = zip.getEntries();entries.hasMoreElements();){
|
||||
ZipEntry entry = (ZipEntry)entries.nextElement();
|
||||
entry.setUnixMode(644); // 解决linux乱码
|
||||
String zipEntryName = entry.getName();
|
||||
InputStream in = zip.getInputStream(entry);
|
||||
String outPath = (unZipDir+zipEntryName).replaceAll("\\*", "/");;
|
||||
//判断路径是否存在,不存在则创建文件路径
|
||||
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
|
||||
if(!file.exists()){
|
||||
file.mkdirs();
|
||||
}
|
||||
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
|
||||
if(new File(outPath).isDirectory()){
|
||||
continue;
|
||||
}
|
||||
//输出文件路径信息
|
||||
//System.out.println(outPath);
|
||||
|
||||
OutputStream out = new FileOutputStream(outPath);
|
||||
byte[] buf1 = new byte[1024];
|
||||
int len;
|
||||
while((len=in.read(buf1))>0){
|
||||
out.write(buf1,0,len);
|
||||
}
|
||||
in.close();
|
||||
out.close();
|
||||
//fileNames.add(zipEntryName);
|
||||
}
|
||||
zip.close();
|
||||
|
||||
listFiles(pathFile);
|
||||
|
||||
// for(String string: excelFiles){
|
||||
// System.out.println(string);
|
||||
// }
|
||||
// for(String string: imageFiles){
|
||||
// System.out.println(string);
|
||||
// }
|
||||
|
||||
filesMap.put("excel",excelFiles);
|
||||
filesMap.put("image",imageFiles);
|
||||
return filesMap;
|
||||
}
|
||||
|
||||
public static void listFiles(File srcDir){
|
||||
// excelFiles.clear();
|
||||
// imageFiles.clear();
|
||||
File[] files = srcDir.listFiles(); //列出所有的子文件
|
||||
for(File file :files)
|
||||
{
|
||||
if(file.isFile())//如果是文件,则输出文件名字
|
||||
{
|
||||
String fileName = file.getAbsolutePath();
|
||||
//判断jpg图片
|
||||
if (fileName.endsWith("jpg") || fileName.endsWith("png")) {
|
||||
imageFiles.add(fileName);
|
||||
}else if(fileName.endsWith("xls") || fileName.endsWith("xlsx")){
|
||||
excelFiles.add(fileName);
|
||||
}
|
||||
}else if(file.isDirectory())//如果是文件夹,则输出文件夹的名字,并递归遍历该文件夹
|
||||
{
|
||||
listFiles(file);//递归遍历
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// public static File[] returnFiles(String strPath) {
|
||||
// File dir = new File(strPath);
|
||||
// File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
|
||||
// if (files != null) {
|
||||
// for (int i = 0; i < files.length; i++) {
|
||||
// String fileName = files[i].getName();
|
||||
// File f = new File(strPath + File.separator + fileName);
|
||||
// System.out.println("文件名称:"+fileName);
|
||||
// if (f.isDirectory()) {// 如果f是目录
|
||||
// File[] newfiles = f.listFiles();
|
||||
// return newfiles;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return files;
|
||||
// }
|
||||
|
||||
|
||||
// public static List<String> copyJpgFiles(File srcDir,String destPath) throws Exception
|
||||
// {
|
||||
// //List<String> copyFileNames = new ArrayList<>();
|
||||
// copyFileNames.clear();
|
||||
// File[] files = srcDir.listFiles(); //列出所有的子文件
|
||||
// for(File file :files)
|
||||
// {
|
||||
// if(file.isFile())//如果是文件,则输出文件名字
|
||||
// {
|
||||
// String fileName = file.getName();
|
||||
// //判断jpg图片
|
||||
// if (fileName.endsWith("jpg")) {
|
||||
// copyFileNames.add(fileName);
|
||||
// FileUtils.copyFile(file, new File(destPath+"/"+fileName));
|
||||
// }
|
||||
// }else if(file.isDirectory())//如果是文件夹,则输出文件夹的名字,并递归遍历该文件夹
|
||||
// {
|
||||
// copyJpgFiles(file,destPath);//递归遍历
|
||||
// }
|
||||
// }
|
||||
// return copyFileNames;
|
||||
// }
|
||||
|
||||
public static void main(String args[]){
|
||||
// try{
|
||||
// File srcDir = new File("D:/images/20190909095419/2019");
|
||||
// List<String> names = copyJpgFiles(srcDir,"D:/images/20190909095419/2020");
|
||||
// String s = "";
|
||||
// }catch (Exception e){
|
||||
//
|
||||
//
|
||||
// }
|
||||
|
||||
try{
|
||||
File srcDir = new File("D:\\project\\cell\\temp\\730349916982870023\\ab028c688f294c74a91ed4290c381afa");
|
||||
listFiles(srcDir);
|
||||
for(String string: CompressZipUtils.getExcelFiles()){
|
||||
System.out.println(string);
|
||||
}
|
||||
for(String string: CompressZipUtils.getImageFiles()){
|
||||
System.out.println(string);
|
||||
}
|
||||
}catch (Exception e){
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
|
||||
|
||||
package net.shapelight.common.utils;
|
||||
|
||||
/**
|
||||
* 系统参数相关Key
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class ConfigConstant {
|
||||
/**
|
||||
* 云存储配置KEY
|
||||
*/
|
||||
public final static String CLOUD_STORAGE_CONFIG_KEY = "CLOUD_STORAGE_CONFIG_KEY";
|
||||
}
|
|
@ -0,0 +1,219 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
/**
|
||||
* 常量
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class Constant {
|
||||
/** 超级管理员ID */
|
||||
public static final int SUPER_ADMIN = 1;
|
||||
//public static final String SUPER_ADMIN = "1";
|
||||
public static final int SYSTEM_ADMIN = 1; //平台超级管理员
|
||||
public static final int SYSTEM_USER = 10; ///平台用户
|
||||
|
||||
public static final int TENANT_ADMIN = 2; /// 运营商
|
||||
public static final int TENANT_USER = 20; // 运营商内用户
|
||||
/** 系统用户标识 */
|
||||
//public static final String SYSTEM_USRE = "sys";
|
||||
/** 企业租户用户标识 */
|
||||
//public static final String TENANT_USER = "ten";
|
||||
/** 企业租户子用户标识 */
|
||||
//public static final String TENSUB_USER = "sub";
|
||||
|
||||
public static final int ROLE_SYS_ADMIN = 100; //平台管理员
|
||||
public static final int ROLE_TEN_ADMIN = 1000; //运营商超级管理
|
||||
public static final int ROLE_TEN_AREA = 2000; //区域管理员 添加小区
|
||||
//public static final int ROLE_TEN_GONGAN = 2100; //公安管理员,添加派出所,派出所关联区域
|
||||
//public static final int ROLE_TEN_PAICHUSUO = 2200; //派出所管理员
|
||||
//public static final int ROLE_TEN_POLICE = 2300; //警员
|
||||
public static final int ROLE_TEN_CELL = 3000; //小区主管 添加楼栋
|
||||
//public static final int ROLE_TEN_BUILD = 4000; //楼栋管理 只能管理某些楼栋
|
||||
|
||||
public static final int PERSON_TYPE_OWNER = 5000; //学生
|
||||
public static final int PERSON_TYPE_MEMBER = 5001; //
|
||||
public static final int PERSON_TYPE_TENANT = 5002; //
|
||||
public static final int PERSON_TYPE_GUEST = 5005; //访客
|
||||
public static final int PERSON_TYPE_PROPERTY = 5006; //教职工
|
||||
public static final int PERSON_TYPE_PARENT = 5007; //家长
|
||||
public static final int PERSON_TYPE_WHITE = 5007; //白名单
|
||||
public static final int PERSON_TYPE_BLACK = 5008; //黑名单
|
||||
public static final int PERSON_TYPE_STUDENT = 5008; //黑名单
|
||||
|
||||
public static final int USER_STATUS_NOMOR = 1; //用户状态,正常
|
||||
public static final int USER_STATUS_DESABLE = 0; //用户状态,禁用
|
||||
|
||||
public static final int APP_LOGIN_YES = 1; //可以App登录
|
||||
public static final int APP_LOGIN_NO = 0; //app不能登录
|
||||
|
||||
public static final int CELL_TYPE_COMMUNITY = 0; //居民小区
|
||||
public static final int CELL_TYPE_SCHOOL = 1; //学校
|
||||
public static final int CELL_TYPE_OFFICE = 2; //办公区
|
||||
|
||||
public static final int ROOM_TYPE_OWNER = 0; //房屋类型 自住房
|
||||
public static final int ROOM_TYPE_TENANT = 1; // 房屋类型 出租房
|
||||
public static final int ROOM_TYPE_shop = 2; //房屋类型 商铺
|
||||
|
||||
public static final int RESGISTER_TYPE_WEB = 1; //web后台添加
|
||||
public static final int RESGISTER_TYPE_APP = 2; //App添加
|
||||
public static final int RESGISTER_TYPE_FILE = 3; //批量导入
|
||||
public static final int RESGISTER_TYPE_Device = 4; //批量导入
|
||||
|
||||
public static final int PESON_SUATUS_NOMOR = 0; //正常
|
||||
public static final int PESON_SUATUS_DISABLE = 1; //禁用
|
||||
public static final int PESON_SUATUS_WAITREVIEW = 2; //待审核
|
||||
public static final int PESON_SUATUS_REJECT = 3; //审核不通过
|
||||
public static final int PESON_SUATUS_FACE_FAILURE = 4; //照片质量不合格
|
||||
public static final int PESON_SUATUS_GUEST_DATE_OUT = 5; //访客已过时
|
||||
|
||||
public static final String IMAGE_DIR_CAR = "car";
|
||||
public static final String IMAGE_DIR_REPAIR= "repair";
|
||||
|
||||
public static final int FACE_FAILURE_OK = 0;
|
||||
public static final int FACE_FAILURE_FAIL = 1;
|
||||
|
||||
public static final String CAR_ENTER_ID = "100";
|
||||
public static final String CAR_EXIT_ID = "200";
|
||||
|
||||
|
||||
/**
|
||||
* 娱乐场所 2
|
||||
* 机关企事 4
|
||||
* 其他 5
|
||||
* 用工单位 42
|
||||
* 出租房 46
|
||||
*/
|
||||
public static final int COMPANY_TYPE_YULE = 2;
|
||||
public static final int COMPANY_TYPE_JIGUAN = 4;
|
||||
public static final int COMPANY_TYPE_QITA = 5;
|
||||
public static final int COMPANY_TYPE_YONGGONG = 42;
|
||||
public static final int COMPANY_TYPE_CHUZU = 46;
|
||||
|
||||
|
||||
//0未同步4已同步1新增2修改3删除
|
||||
public static final int PERSON_SYNC_NO = 0;
|
||||
public static final int PERSON_SYNC_OK = 4;
|
||||
public static final int PERSON_SYNC_ADD = 1;
|
||||
public static final int PERSON_SYNC_MODIFY = 2;
|
||||
public static final int PERSON_SYNC_DELETE = 3;
|
||||
|
||||
public static final String DEVICE_FLAG_2D = "0";
|
||||
public static final String DEVICE_FLAG_3D = "1";
|
||||
|
||||
//上班状态0缺卡1正常2迟到 下班状态0缺卡1正常3早退
|
||||
public static final int CHECK_QUEKA =0;
|
||||
public static final int CHECK_OK =1;
|
||||
public static final int CHECK_CHIDAO =2;
|
||||
public static final int CHECK_ZAOTUI =3;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public static final String DB2 = "db2";
|
||||
/** 数据权限过滤 */
|
||||
public static final String SQL_FILTER = "sql_filter";
|
||||
/**
|
||||
* 当前页码
|
||||
*/
|
||||
public static final String PAGE = "page";
|
||||
/**
|
||||
* 每页显示记录数
|
||||
*/
|
||||
public static final String LIMIT = "limit";
|
||||
/**
|
||||
* 排序字段
|
||||
*/
|
||||
public static final String ORDER_FIELD = "sidx";
|
||||
/**
|
||||
* 排序方式
|
||||
*/
|
||||
public static final String ORDER = "order";
|
||||
/**
|
||||
* 升序
|
||||
*/
|
||||
public static final String ASC = "asc";
|
||||
|
||||
/**
|
||||
* 菜单类型
|
||||
*/
|
||||
public enum MenuType {
|
||||
/**
|
||||
* 目录
|
||||
*/
|
||||
CATALOG(0),
|
||||
/**
|
||||
* 菜单
|
||||
*/
|
||||
MENU(1),
|
||||
/**
|
||||
* 按钮
|
||||
*/
|
||||
BUTTON(2);
|
||||
|
||||
private int value;
|
||||
|
||||
MenuType(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时任务状态
|
||||
*/
|
||||
public enum ScheduleStatus {
|
||||
/**
|
||||
* 正常
|
||||
*/
|
||||
NORMAL(0),
|
||||
/**
|
||||
* 暂停
|
||||
*/
|
||||
PAUSE(1);
|
||||
|
||||
private int value;
|
||||
|
||||
ScheduleStatus(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 云服务商
|
||||
*/
|
||||
public enum CloudService {
|
||||
/**
|
||||
* 七牛云
|
||||
*/
|
||||
QINIU(1),
|
||||
/**
|
||||
* 阿里云
|
||||
*/
|
||||
ALIYUN(2),
|
||||
/**
|
||||
* 腾讯云
|
||||
*/
|
||||
QCLOUD(3);
|
||||
|
||||
private int value;
|
||||
|
||||
CloudService(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,46 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import com.guwan.excel.EasyExcel;
|
||||
import com.guwan.excel.converters.longconverter.LongStringConverter;
|
||||
import com.guwan.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
public class ExcelUtils {
|
||||
|
||||
/**
|
||||
* 将列表以 Excel 响应给前端
|
||||
*
|
||||
* @param response 响应
|
||||
* @param filename 文件名
|
||||
* @param sheetName Excel sheet 名
|
||||
* @param head Excel head 头
|
||||
* @param data 数据列表
|
||||
* @param <T> 泛型,保证 head 和 data 类型的一致性
|
||||
* @throws IOException 写入失败的情况
|
||||
*/
|
||||
public static <T> void write(HttpServletResponse response, String filename, String sheetName,
|
||||
Class<T> head, List<T> data) throws IOException {
|
||||
// 输出 Excel
|
||||
EasyExcel.write(response.getOutputStream(), head)
|
||||
.autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
|
||||
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 基于 column 长度,自动适配。最大 255 宽度
|
||||
.registerConverter(new LongStringConverter()) // 避免 Long 类型丢失精度
|
||||
.sheet(sheetName).doWrite(data);
|
||||
// 设置 header 和 contentType。写在最后的原因是,避免报错时,响应 contentType 已经被修改了
|
||||
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
|
||||
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
|
||||
}
|
||||
|
||||
public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
|
||||
return EasyExcel.read(file.getInputStream(), head, null)
|
||||
.autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
|
||||
.doReadAllSync();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,260 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author benny
|
||||
* @Description TODO:文件上传工具类
|
||||
* @date 2019-05-28
|
||||
*/
|
||||
@Component
|
||||
public class FileUploadUtils
|
||||
{
|
||||
/**
|
||||
* 默认大小 10M
|
||||
*/
|
||||
public static final long DEFAULT_MAX_SIZE = 10 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* 默认的文件名最大长度 100
|
||||
*/
|
||||
public static final int DEFAULT_FILE_NAME_LENGTH = 100;
|
||||
|
||||
/**
|
||||
* 上传的地址
|
||||
*
|
||||
* file:
|
||||
* #文件上传目录(注意Linux和Windows上的目录结构不同)
|
||||
* uploadPath: /home/shapelight/upload
|
||||
*
|
||||
*/
|
||||
private static String defaultBaseDir;
|
||||
private static int counter = 0;
|
||||
|
||||
|
||||
public static String getDefaultBaseDir() {
|
||||
return defaultBaseDir;
|
||||
}
|
||||
|
||||
// @Value("${file.uploadPath}")
|
||||
// public void setDefaultBaseDir(String defaultBaseDir) {
|
||||
// FileUploadUtils.defaultBaseDir = defaultBaseDir;
|
||||
// }
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description TODO:以默认配置进行文件上传
|
||||
* @date 2019-05-28
|
||||
* @param file
|
||||
* @return java.lang.String
|
||||
*/
|
||||
public static final String uploadImage(MultipartFile file) throws Exception
|
||||
{
|
||||
try
|
||||
{
|
||||
return upload(getDefaultBaseDir(), file, MimeTypeUtils.IMAGE_EXTENSION);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new Exception(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public static final String uploadImage(String baseDir,MultipartFile file) throws Exception
|
||||
{
|
||||
try
|
||||
{
|
||||
return upload(getDefaultBaseDir(), file, MimeTypeUtils.IMAGE_EXTENSION);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new Exception(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description TODO:上传视频
|
||||
* @date 2019-05-28
|
||||
* @param file
|
||||
* @return java.lang.String
|
||||
*/
|
||||
public static final String uploadMedia(MultipartFile file) throws Exception
|
||||
{
|
||||
try
|
||||
{
|
||||
return upload(getDefaultBaseDir(), file, MimeTypeUtils.MEDIA_EXTENSION);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new Exception(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description TODO:根据路径上传文件
|
||||
* @date 2019-05-28
|
||||
* @param baseDir
|
||||
* @param file
|
||||
* @return java.lang.String
|
||||
*/
|
||||
/*public static final String upload(String baseDir, MultipartFile file) throws Exception
|
||||
{
|
||||
try
|
||||
{
|
||||
return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new Exception(e.getMessage(), e);
|
||||
}
|
||||
}*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description TODO:上传文件
|
||||
* @date 2019-05-28
|
||||
* @param baseDir 上传目录
|
||||
* @param file 上传文件
|
||||
* @param allowedExtension 允许的文件格式
|
||||
* @return java.lang.String 返回文件名
|
||||
*/
|
||||
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
|
||||
throws Exception
|
||||
{
|
||||
int fileNamelength = file.getOriginalFilename().length();
|
||||
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
|
||||
{
|
||||
throw new Exception("文件名过长"+ FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
|
||||
}
|
||||
assertAllowed(file, allowedExtension);
|
||||
String fileName = extractFilename(file);
|
||||
File desc = getAbsoluteFile(baseDir, fileName);
|
||||
file.transferTo(desc);
|
||||
return fileName;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description TODO:编码文件名
|
||||
* @date 2019-05-28
|
||||
* @param file
|
||||
* @return java.lang.String
|
||||
*/
|
||||
public static final String extractFilename(MultipartFile file)
|
||||
{
|
||||
String filename = file.getOriginalFilename();
|
||||
String extension = getExtension(file);
|
||||
//filename = DateUtils.datePath() + "/" + encodingFilename(filename) + "." + extension;
|
||||
filename = encodingFilename(filename) + "." + extension;
|
||||
//filename = UUIDUtil.uuid() + "." + extension;
|
||||
return filename;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description TODO:上传文件路径
|
||||
* @date 2019-05-28
|
||||
* @param uploadDir
|
||||
* @param filename
|
||||
* @return java.io.File
|
||||
*/
|
||||
private static final File getAbsoluteFile(String uploadDir, String filename) throws Exception
|
||||
{
|
||||
File desc = new File(uploadDir + File.separator + filename);
|
||||
|
||||
if (!desc.getParentFile().exists())
|
||||
{
|
||||
desc.getParentFile().mkdirs();
|
||||
}
|
||||
if (!desc.exists())
|
||||
{
|
||||
desc.createNewFile();
|
||||
}
|
||||
return desc;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description TODO:编码文件名
|
||||
* @date 2019-05-28
|
||||
* @param filename
|
||||
* @return java.lang.String
|
||||
*/
|
||||
private static final String encodingFilename(String filename)
|
||||
{
|
||||
filename = filename.replace("_", " ");
|
||||
filename = MD5Utils.hash(filename + System.nanoTime() + counter++);
|
||||
return filename;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description TODO:文件大小校验
|
||||
* @date 2019-05-28
|
||||
* @param file
|
||||
* @param allowedExtension
|
||||
* @return void
|
||||
*/
|
||||
public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
|
||||
throws Exception
|
||||
{
|
||||
long size = file.getSize();
|
||||
if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE)
|
||||
{
|
||||
throw new Exception("文件过大,最大允许:"+(DEFAULT_MAX_SIZE / 1024 / 1024)+"M");
|
||||
}
|
||||
String extension = getExtension(file);
|
||||
if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
|
||||
{
|
||||
throw new Exception("文件类型错误");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description TODO:判断MIME类型是否是允许的MIME类型
|
||||
* @date 2019-05-28
|
||||
* @param extension
|
||||
* @param allowedExtension
|
||||
* @return boolean
|
||||
*/
|
||||
public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
|
||||
{
|
||||
for (String str : allowedExtension)
|
||||
{
|
||||
if (str.equalsIgnoreCase(extension))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description TODO:获取文件名的后缀
|
||||
* @date 2019-05-28
|
||||
* @param file
|
||||
* @return java.lang.String 后缀名
|
||||
*/
|
||||
public static final String getExtension(MultipartFile file)
|
||||
{
|
||||
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
|
||||
if (StringUtils.isEmpty(extension))
|
||||
{
|
||||
extension = MimeTypeUtils.getExtension(file.getContentType());
|
||||
}
|
||||
return extension;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,164 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.codehaus.jackson.map.ObjectMapper;
|
||||
import org.codehaus.jackson.map.annotate.JsonSerialize;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* HTTP 请求工具类
|
||||
*
|
||||
* @author Simon
|
||||
* @date 2018年7月23日
|
||||
*/
|
||||
|
||||
@Slf4j
|
||||
public class HttpConnectionUtils {
|
||||
private HttpConnectionUtils() {
|
||||
}
|
||||
|
||||
/**
|
||||
* post 请求封装
|
||||
*
|
||||
* @param value
|
||||
* @param URL
|
||||
* @return
|
||||
*/
|
||||
|
||||
public static JSONObject post(final Object value, final String URL) {
|
||||
|
||||
if (!StringUtils.isNotBlank(URL)) {
|
||||
return null;
|
||||
|
||||
}
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
|
||||
String requestJson = null;
|
||||
try {
|
||||
requestJson = objectMapper.writeValueAsString(value);
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
e.printStackTrace();
|
||||
|
||||
}
|
||||
|
||||
log.info("requestJson:{}", requestJson);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
|
||||
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
|
||||
requestFactory.setConnectTimeout(180000);// 设置超时
|
||||
requestFactory.setReadTimeout(180000);
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
log.info("URL:{}", URL);
|
||||
ResponseEntity<String> response = restTemplate.exchange(URL, HttpMethod.POST, entity, String.class);
|
||||
Integer code = response.getStatusCode().value();
|
||||
if (200 != code) {
|
||||
|
||||
//错误返回值处理
|
||||
|
||||
}
|
||||
|
||||
JSONObject body = new JSONObject().parseObject(response.getBody());
|
||||
log.info("body:{}", body);
|
||||
return body;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* get请求封装
|
||||
*
|
||||
* @param uriComponents
|
||||
* @return
|
||||
*/
|
||||
|
||||
public static JSONObject get(final UriComponents uriComponents) {
|
||||
|
||||
if (null == uriComponents) {
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
|
||||
requestFactory.setReadTimeout(5000);
|
||||
requestFactory.setConnectTimeout(5000);
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
URI uri = uriComponents.toUri();
|
||||
log.info(uri.toString());
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
|
||||
Integer code = response.getStatusCode().value();
|
||||
if (200 != code) {
|
||||
|
||||
//错误返回值处理
|
||||
|
||||
}
|
||||
|
||||
JSONObject body = new JSONObject().parseObject(response.getBody());
|
||||
log.info("body:{}", body);
|
||||
return body;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* delete请求封装
|
||||
*
|
||||
* @param URL
|
||||
* @param map
|
||||
* @return
|
||||
*/
|
||||
|
||||
public static JSONObject delete(final String URL,final Map<String, Object> map) {
|
||||
|
||||
if (!StringUtils.isNotBlank(URL)) {
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
log.info("URL:{}", URL);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
|
||||
HttpEntity<String> entity = new HttpEntity<String>(null, headers);
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
|
||||
requestFactory.setConnectTimeout(180000);// 设置超时
|
||||
requestFactory.setReadTimeout(180000);
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
ResponseEntity<String> response = restTemplate.exchange(URL, HttpMethod.DELETE, entity, String.class, map);
|
||||
Integer code = response.getStatusCode().value();
|
||||
|
||||
if (200 != code) {
|
||||
|
||||
//错误返回值处理
|
||||
|
||||
}
|
||||
JSONObject body = new JSONObject().parseObject(response.getBody());
|
||||
log.info("body:{}", body);
|
||||
return body;
|
||||
|
||||
}
|
||||
|
||||
public static void main(String args[]){
|
||||
Map<String, Object> ser = new HashMap();
|
||||
ser.put("serial","NG0mV1kpuY9WQ7PryPME5Tcz85JtwTHZ");
|
||||
JSONObject res = post(ser,"http://39.96.9.232:3389/getSerialInfo");
|
||||
log.info(res.toJSONString());
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
public class HttpContextUtils {
|
||||
|
||||
public static HttpServletRequest getHttpServletRequest() {
|
||||
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
||||
}
|
||||
|
||||
public static String getDomain(){
|
||||
HttpServletRequest request = getHttpServletRequest();
|
||||
StringBuffer url = request.getRequestURL();
|
||||
return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
|
||||
}
|
||||
|
||||
public static String getOrigin(){
|
||||
HttpServletRequest request = getHttpServletRequest();
|
||||
return request.getHeader("Origin");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,131 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
|
||||
import javax.net.ssl.*;
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.InetAddress;
|
||||
import java.net.Socket;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
/**
|
||||
* Created by huangquanwei on 2019/6/1 10:30
|
||||
* Https 绕过
|
||||
*/
|
||||
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
|
||||
|
||||
|
||||
@Override
|
||||
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
|
||||
try {
|
||||
if (!(connection instanceof HttpsURLConnection)) {
|
||||
throw new RuntimeException("An instance of HttpsURLConnection is expected");
|
||||
}
|
||||
|
||||
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
|
||||
|
||||
TrustManager[] trustAllCerts = new TrustManager[]{
|
||||
new X509TrustManager() {
|
||||
@Override
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public void checkClientTrusted(X509Certificate[] certs, String authType) {
|
||||
}
|
||||
@Override
|
||||
public void checkServerTrusted(X509Certificate[] certs, String authType) {
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
|
||||
httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
|
||||
|
||||
httpsConnection.setHostnameVerifier(new HostnameVerifier() {
|
||||
@Override
|
||||
public boolean verify(String s, SSLSession sslSession) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
super.prepareConnection(httpsConnection, httpMethod);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
|
||||
* see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
|
||||
*/
|
||||
// SSLSocketFactory用于创建 SSLSockets
|
||||
private static class MyCustomSSLSocketFactory extends SSLSocketFactory {
|
||||
|
||||
private final SSLSocketFactory delegate;
|
||||
|
||||
public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
// 返回默认启用的密码套件。除非一个列表启用,对SSL连接的握手会使用这些密码套件。
|
||||
// 这些默认的服务的最低质量要求保密保护和服务器身份验证
|
||||
@Override
|
||||
public String[] getDefaultCipherSuites() {
|
||||
return delegate.getDefaultCipherSuites();
|
||||
}
|
||||
|
||||
// 返回的密码套件可用于SSL连接启用的名字
|
||||
@Override
|
||||
public String[] getSupportedCipherSuites() {
|
||||
return delegate.getSupportedCipherSuites();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Socket createSocket(final Socket socket, final String host, final int port,
|
||||
final boolean autoClose) throws IOException {
|
||||
final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
|
||||
return overrideProtocol(underlyingSocket);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Socket createSocket(final String host, final int port) throws IOException {
|
||||
final Socket underlyingSocket = delegate.createSocket(host, port);
|
||||
return overrideProtocol(underlyingSocket);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
|
||||
final int localPort) throws
|
||||
IOException {
|
||||
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
|
||||
return overrideProtocol(underlyingSocket);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Socket createSocket(final InetAddress host, final int port) throws IOException {
|
||||
final Socket underlyingSocket = delegate.createSocket(host, port);
|
||||
return overrideProtocol(underlyingSocket);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress,
|
||||
final int localPort) throws
|
||||
IOException {
|
||||
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
|
||||
return overrideProtocol(underlyingSocket);
|
||||
}
|
||||
|
||||
private Socket overrideProtocol(final Socket socket) {
|
||||
if (!(socket instanceof SSLSocket)) {
|
||||
throw new RuntimeException("An instance of SSLSocket is expected");
|
||||
}
|
||||
((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1"});
|
||||
return socket;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collection;
|
||||
|
||||
public interface ITree {
|
||||
/**
|
||||
* 获取被依赖节点
|
||||
* @return
|
||||
*/
|
||||
Serializable getId();
|
||||
|
||||
/**
|
||||
* 设置被依赖节点
|
||||
* @param id
|
||||
*/
|
||||
void setId(Serializable id);
|
||||
|
||||
/**
|
||||
* 获取依赖节点
|
||||
* @return
|
||||
*/
|
||||
Serializable getParent();
|
||||
|
||||
/**
|
||||
* 设置依赖节点
|
||||
* @param parent
|
||||
*/
|
||||
void setParent(Serializable parent);
|
||||
|
||||
/**
|
||||
* 获取孩子列表
|
||||
* @return
|
||||
*/
|
||||
Collection<? extends ITree> getChildren();
|
||||
|
||||
/**
|
||||
* 设置孩子列表
|
||||
* @param children
|
||||
*/
|
||||
void setChildren(Collection<? extends ITree> children);
|
||||
}
|
||||
|
|
@ -0,0 +1,193 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import net.coobird.thumbnailator.Thumbnails;
|
||||
import net.coobird.thumbnailator.geometry.Positions;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.font.FontRenderContext;
|
||||
import java.awt.font.TextAttribute;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.text.AttributedCharacterIterator;
|
||||
import java.text.AttributedString;
|
||||
|
||||
/**
|
||||
* 图像工具类
|
||||
*/
|
||||
public class ImageUtil {
|
||||
private static final Logger log = LoggerFactory.getLogger(ImageUtil.class);
|
||||
//压缩率
|
||||
private static final transient float IMAGE_RATIO = 0.1f;
|
||||
//压缩最大宽度
|
||||
private static final transient int IMAGE_WIDTH = 800;
|
||||
// 水印透明度
|
||||
private static float alpha = 0.3f;
|
||||
// 水印文字字体
|
||||
private static Font font = new Font("PingFang SC Regular", Font.PLAIN, 36);
|
||||
// 水印文字颜色
|
||||
private static Color color = new Color(111, 111, 111);
|
||||
//水印文字内容
|
||||
private static final String text = "这是一个水印文本";
|
||||
// 水印之间的间隔
|
||||
private static final int XMOVE = 80;
|
||||
// 水印之间的间隔
|
||||
private static final int YMOVE = 80;
|
||||
|
||||
/**
|
||||
* 压缩图像
|
||||
*
|
||||
* @param image
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static BufferedImage compress(BufferedImage image) throws IOException {
|
||||
Thumbnails.Builder<BufferedImage> imageBuilder = Thumbnails.of(image).outputQuality(IMAGE_RATIO);
|
||||
if (image.getWidth() > IMAGE_WIDTH) {
|
||||
return imageBuilder.width(IMAGE_WIDTH).asBufferedImage();
|
||||
} else {
|
||||
return imageBuilder.scale(1).asBufferedImage();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 图像添加水印
|
||||
*
|
||||
* @param
|
||||
* @return
|
||||
*/
|
||||
public static BufferedImage setWatermark(BufferedImage image) throws IOException {
|
||||
return Thumbnails.of(image)
|
||||
.outputQuality(IMAGE_RATIO)
|
||||
.scale(1)
|
||||
.watermark(Positions.BOTTOM_RIGHT
|
||||
, createWatermark(text
|
||||
, image.getWidth()
|
||||
, image.getHeight()
|
||||
)
|
||||
, alpha)
|
||||
.asBufferedImage();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文件扩展名判断文件是否图片格式
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static boolean isImage(String fileName) {
|
||||
String[] imageExtension = new String[]{"jpeg", "jpg", "gif", "bmp", "png"};
|
||||
|
||||
for (String e : imageExtension) if (getFileExtention(fileName).toLowerCase().equals(e)) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件后缀名称
|
||||
*
|
||||
* @param fileName
|
||||
* @return
|
||||
*/
|
||||
public static String getFileExtention(String fileName) {
|
||||
String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
|
||||
return extension;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据图片对象获取对应InputStream
|
||||
*
|
||||
* @param image
|
||||
* @param readImageFormat
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static InputStream getInputStream(BufferedImage image, String readImageFormat) throws IOException {
|
||||
ByteArrayOutputStream os = new ByteArrayOutputStream();
|
||||
ImageIO.write(image, readImageFormat, os);
|
||||
InputStream is = new ByteArrayInputStream(os.toByteArray());
|
||||
os.close();
|
||||
return is;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建水印图片
|
||||
*
|
||||
* @param text 水印文字
|
||||
* @param width 图片宽
|
||||
* @param height 图片高
|
||||
* @return
|
||||
*/
|
||||
public static BufferedImage createWatermark(String text, int width, int height) {
|
||||
BufferedImage image = new BufferedImage(width
|
||||
, height, BufferedImage.TYPE_INT_RGB);
|
||||
// 2.获取图片画笔
|
||||
Graphics2D g = image.createGraphics();
|
||||
// ---------- 增加下面的代码使得背景透明 -----------------
|
||||
image = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
|
||||
g.dispose();
|
||||
g = image.createGraphics();
|
||||
// ---------- 背景透明代码结束 -----------------
|
||||
// 6、处理文字
|
||||
AttributedString ats = new AttributedString(text);
|
||||
ats.addAttribute(TextAttribute.FONT, font, 0, text.length());
|
||||
AttributedCharacterIterator iter = ats.getIterator();
|
||||
// 7、设置对线段的锯齿状边缘处理
|
||||
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
// 8、设置水印旋转
|
||||
g.rotate(Math.toRadians(-30));
|
||||
// 9、设置水印文字颜色
|
||||
g.setColor(color);
|
||||
// 10、设置水印文字Font
|
||||
g.setFont(font);
|
||||
// 11、设置水印文字透明度
|
||||
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
|
||||
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
|
||||
/**
|
||||
* 水印铺满图片
|
||||
* 计算水印位置
|
||||
*/
|
||||
int x = -width / 2;
|
||||
int y = -height / 2;
|
||||
int[] arr = getWidthAndHeight(text, font);
|
||||
int markWidth = arr[0];// 字体长度
|
||||
int markHeight = arr[1];// 字体高度
|
||||
// 循环添加水印
|
||||
while (x < width * 1.5) {
|
||||
y = -height / 2;
|
||||
while (y < height * 1.5) {
|
||||
g.drawString(text, x, y);
|
||||
|
||||
y += markHeight + YMOVE;
|
||||
}
|
||||
x += markWidth + XMOVE;
|
||||
}
|
||||
// 13、释放资源
|
||||
g.dispose();
|
||||
return image;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算字体宽度及高度
|
||||
*
|
||||
* @param text
|
||||
* @param font
|
||||
* @return
|
||||
*/
|
||||
private static int[] getWidthAndHeight(String text, Font font) {
|
||||
Rectangle2D r = font.getStringBounds(text, new FontRenderContext(
|
||||
AffineTransform.getScaleInstance(1, 1), false, false));
|
||||
int unitHeight = (int) Math.floor(r.getHeight());//
|
||||
// 获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度
|
||||
int width = (int) Math.round(r.getWidth()) + 1;
|
||||
// 把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度
|
||||
int height = unitHeight + 3;
|
||||
return new int[]{width, height};
|
||||
}
|
||||
}
|
|
@ -0,0 +1,338 @@
|
|||
package net.shapelight.common.utils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.imageio.stream.FileImageInputStream;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public class ImageUtils {
|
||||
/**
|
||||
* 图片转化成base64字符串
|
||||
* @param imgPath
|
||||
* @return
|
||||
*/
|
||||
public static String GetImageBase64Str(String imgPath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
|
||||
String imgFile = imgPath;// 待处理的图片
|
||||
InputStream in = null;
|
||||
byte[] data = null;
|
||||
String encode = null; // 返回Base64编码过的字节数组字符串
|
||||
// 对字节数组Base64编码
|
||||
try {
|
||||
// 读取图片字节数组
|
||||
in = new FileInputStream(imgFile);
|
||||
data = new byte[in.available()];
|
||||
in.read(data);
|
||||
encode = Base64.getEncoder().encodeToString(data);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
in.close();
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return encode;
|
||||
}
|
||||
|
||||
/**
|
||||
* base64字符串转化成图片
|
||||
*
|
||||
* @param imgData
|
||||
* 图片编码
|
||||
* @param imgFilePath
|
||||
* 存放到本地路径
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
@SuppressWarnings("finally")
|
||||
public static boolean Base64StrToImage(String imgData, String imgFilePath) throws IOException { // 对字节数组字符串进行Base64解码并生成图片
|
||||
if (imgData == null) // 图像数据为空
|
||||
return false;
|
||||
OutputStream out = null;
|
||||
try {
|
||||
out = new FileOutputStream(imgFilePath);
|
||||
// Base64解码
|
||||
byte[] b = Base64.getDecoder().decode(imgData.replace("\n",""));
|
||||
/*for (int i = 0; i < b.length; ++i) {
|
||||
if (b[i] < 0) {// 调整异常数据
|
||||
b[i] += 256;
|
||||
}
|
||||
}*/
|
||||
out.write(b);
|
||||
} catch (FileNotFoundException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
out.flush();
|
||||
out.close();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 通过BufferedImage图片流调整图片大小
|
||||
*/
|
||||
public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
|
||||
Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT);
|
||||
BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
|
||||
outputImage.getGraphics().drawImage(resultingImage, 0, 0, null);
|
||||
return outputImage;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* BufferedImage图片流转byte[]数组
|
||||
*/
|
||||
public static byte[] imageToBytes(BufferedImage bImage) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try {
|
||||
ImageIO.write(bImage, "jpg", out);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
|
||||
//图片到byte数组
|
||||
public static byte[] image2byte(String path){
|
||||
byte[] data = null;
|
||||
FileImageInputStream input = null;
|
||||
try {
|
||||
input = new FileImageInputStream(new File(path));
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
byte[] buf = new byte[1024];
|
||||
int numBytesRead = 0;
|
||||
while ((numBytesRead = input.read(buf)) != -1) {
|
||||
output.write(buf, 0, numBytesRead);
|
||||
}
|
||||
data = output.toByteArray();
|
||||
output.close();
|
||||
input.close();
|
||||
}
|
||||
catch (FileNotFoundException ex1) {
|
||||
ex1.printStackTrace();
|
||||
}
|
||||
catch (IOException ex1) {
|
||||
ex1.printStackTrace();
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
public static byte[] getNV21(BufferedImage bufferedImage) {
|
||||
// BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imageData));
|
||||
int width = bufferedImage.getWidth();
|
||||
int height = bufferedImage.getHeight();
|
||||
int[] pixels = bufferedImage.getRGB(0, 0, width, height, null, 0, width);
|
||||
byte[] yuvs = encodeYUV420SP(pixels, width, height);
|
||||
return yuvs;
|
||||
}
|
||||
|
||||
/**
|
||||
* nv21 先u后v
|
||||
*
|
||||
* @return
|
||||
* @paramargb
|
||||
* @paramwidth
|
||||
* @paramheight
|
||||
*/
|
||||
|
||||
public static byte[] encodeYUV420SP(int[] argb, int width, int height) {
|
||||
int size = (int) ((Math.ceil(width / 2.0)) * (Math.ceil(height / 2.0)));
|
||||
int frameSize = width * height;
|
||||
byte[] yuvs = new byte[frameSize + size * 2];
|
||||
int y = 0, u = 0, v = 0;
|
||||
int r = 0, g = 0, b = 0, a = 0;
|
||||
int index = 0, uvindex = frameSize;
|
||||
for (int i = 0; i < height; i++) {
|
||||
for (int j = 0; j < width; j++) {
|
||||
a = (argb[index] & 0xff000000) >> 24;// a is not used obviously
|
||||
r = (argb[index] & 0xff0000) >> 16;
|
||||
g = (argb[index] & 0xff00) >> 8;
|
||||
b = (argb[index] & 0xff) >> 0;
|
||||
//转换公式
|
||||
y = (int) (0.299 * r + 0.587 * g + 0.114 * b);
|
||||
u = (int) (-0.1687 * r - 0.3313 * g + 0.5 * b + 128);
|
||||
v = (int) (0.5 * r - 0.4187 * g - 0.0813 * b + 128);
|
||||
// System.out.println("x:" + i + "y:" + j + " y:" + y + " u:" + u + " v:" + v);
|
||||
yuvs[index++] = (byte) ((y < 0) ? 0 : ((y > 255) ? 255 : y));
|
||||
if (i % 2 == 0 && j % 2 == 0) {
|
||||
yuvs[uvindex++] = (byte) ((u < 0) ? 0 : ((u > 255) ? 255 : u));
|
||||
yuvs[uvindex++] = (byte) ((v < 0) ? 0 : ((v > 255) ? 255 : v));
|
||||
// yuvs[uvindex++]=(byte)120;
|
||||
// yuvs[uvindex++] = (byte) ((v < 0) ? 0 : ((v > 255) ? 255 : v));
|
||||
// yuvs[uvindex++]=(byte)240;
|
||||
}
|
||||
}
|
||||
}
|
||||
return yuvs;
|
||||
}
|
||||
|
||||
public static int[] decodeYUV420sp(byte[] yuvs, int width, int height) {
|
||||
int frameSize = width * height;
|
||||
int[] rgbs = new int[frameSize];
|
||||
int index = 0;
|
||||
int uvindex = frameSize;
|
||||
int u = 0, v = 0, y = 0;
|
||||
for (int i = 0; i < height; i++) {
|
||||
for (int j = 0; j < width; j++) {
|
||||
if (i % 2 == 0 && j % 2 == 0) {
|
||||
u = yuvs[uvindex++];
|
||||
v = yuvs[uvindex++];
|
||||
}
|
||||
//保存到数组中去
|
||||
y = yuvs[index];
|
||||
rgbs[index++] = yuv2Rgb(y, u, v);
|
||||
}
|
||||
}
|
||||
return rgbs;
|
||||
}
|
||||
|
||||
public static int yuv2Rgb(int y, int u, int v) {
|
||||
// 转换公式
|
||||
int r = (int) ((y & 0xff) + 1.402 * ((v & 0xff) - 128));
|
||||
int g = (int) ((y & 0xff) - 0.34414 * ((u & 0xff) - 128) - 0.71414 * ((v & 0xff) - 128));
|
||||
int b = (int) ((y & 0xff) + 1.772 * ((u & 0xff) - 128));
|
||||
r = (r < 0 ? 0 : r > 255 ? 255 : r);
|
||||
g = (g < 0 ? 0 : g > 255 ? 255 : g);
|
||||
b = (b < 0 ? 0 : b > 255 ? 255 : b);
|
||||
return (0xff << 24) + (r << 16) + (g << 8) + b;
|
||||
}
|
||||
|
||||
|
||||
// public static void main(String[] args) {
|
||||
//
|
||||
//// File imgFile = new File("/home/huangyifang/gb/palm/noface.jpg");
|
||||
// String path = "/home/huangyifang/gb/palm/noface.jpg";
|
||||
// byte[] imageData = image2byte(path);
|
||||
// try {
|
||||
// BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imageData));
|
||||
// byte[] nv21 = getNV21(bufferedImage);
|
||||
// System.out.println("000000000000000000");
|
||||
// }catch (Exception e){
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
// String imageStr = GetImageBase64Str("d:/3.jpg");
|
||||
// System.out.println(imageStr);
|
||||
// Base64StrToImage(imageStr, "deviceEntity");
|
||||
|
||||
|
||||
|
||||
File img = new File("d:/3.jpg");
|
||||
if(img.exists()){
|
||||
String faceStr = ImageUtils.GetImageBase64Str("d:/3.jpg");
|
||||
|
||||
long now = new Date().getTime();
|
||||
String a = faceStr;
|
||||
}else{
|
||||
String a = "";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void saveMultiFile(MultipartFile mFile, String destFile) throws Exception{
|
||||
InputStream in_left0 = mFile.getInputStream();
|
||||
OutputStream os_left0 = new FileOutputStream(destFile);
|
||||
int bytesRead = 0;
|
||||
byte[] buffer = new byte[8192];
|
||||
while ((bytesRead = in_left0.read(buffer, 0, 8192)) != -1) {
|
||||
os_left0.write(buffer, 0, bytesRead);
|
||||
}
|
||||
os_left0.close();
|
||||
in_left0.close();
|
||||
}
|
||||
|
||||
|
||||
public static void main2(String[] args) {
|
||||
String zipFileName = "example.zip";
|
||||
String folderToCompress = "folder";
|
||||
|
||||
try (
|
||||
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName))) {
|
||||
// 压缩文件夹
|
||||
compressFolder(folderToCompress, folderToCompress, zipOutputStream);
|
||||
|
||||
System.out.println("Folder compressed successfully!");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void compressFolder(String sourceFolder, String folderName, ZipOutputStream zipOutputStream) throws IOException {
|
||||
File folder = new File(sourceFolder);
|
||||
File[] files = folder.listFiles();
|
||||
|
||||
if (files != null) {
|
||||
for (File file : files) {
|
||||
if (file.isDirectory()) {
|
||||
// 压缩子文件夹
|
||||
compressFolder(file.getAbsolutePath(), folderName + "/" + file.getName(), zipOutputStream);
|
||||
} else {
|
||||
// 压缩文件
|
||||
addToZipFile(folderName + "/" + file.getName(), file.getAbsolutePath(), zipOutputStream);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void addToZipFile(String fileName, String fileAbsolutePath, ZipOutputStream zipOutputStream) throws IOException {
|
||||
// 创建ZipEntry对象并设置文件名
|
||||
ZipEntry entry = new ZipEntry(fileName);
|
||||
zipOutputStream.putNextEntry(entry);
|
||||
|
||||
// 读取文件内容并写入Zip文件
|
||||
try (FileInputStream fileInputStream = new FileInputStream(fileAbsolutePath)) {
|
||||
byte[] buffer = new byte[1024];
|
||||
int bytesRead;
|
||||
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
|
||||
zipOutputStream.write(buffer, 0, bytesRead);
|
||||
}
|
||||
}
|
||||
// 完成当前文件的压缩
|
||||
zipOutputStream.closeEntry();
|
||||
}
|
||||
|
||||
public static void createDir(String dir){
|
||||
File folder = new File(dir);
|
||||
// 判断文件夹是否存在
|
||||
if (!folder.exists()) {
|
||||
// 创建文件夹
|
||||
boolean result = folder.mkdirs();
|
||||
if (result) {
|
||||
System.out.println("文件夹创建成功");
|
||||
} else {
|
||||
System.out.println("文件夹创建失败");
|
||||
}
|
||||
} else {
|
||||
System.out.println("文件夹已存在");
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteFolder(File folder) {
|
||||
if (folder.isDirectory()) {
|
||||
File[] files = folder.listFiles();
|
||||
if (files != null) {
|
||||
for (File file : files) {
|
||||
deleteFolder(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
folder.delete();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,189 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
/**
|
||||
* 获取IP方法
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class IpUtils
|
||||
{
|
||||
public static String getIpAddr(HttpServletRequest request)
|
||||
{
|
||||
if (request == null)
|
||||
{
|
||||
return "unknown";
|
||||
}
|
||||
String ip = request.getHeader("x-forwarded-for");
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
|
||||
{
|
||||
ip = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
|
||||
{
|
||||
ip = request.getHeader("X-Forwarded-For");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
|
||||
{
|
||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
|
||||
{
|
||||
ip = request.getHeader("X-Real-IP");
|
||||
}
|
||||
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
|
||||
{
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
|
||||
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
|
||||
}
|
||||
|
||||
public static boolean internalIp(String ip)
|
||||
{
|
||||
byte[] addr = textToNumericFormatV4(ip);
|
||||
return internalIp(addr) || "127.0.0.1".equals(ip);
|
||||
}
|
||||
|
||||
private static boolean internalIp(byte[] addr)
|
||||
{
|
||||
if (StringUtils.isNull(addr) || addr.length < 2)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
final byte b0 = addr[0];
|
||||
final byte b1 = addr[1];
|
||||
// 10.x.x.x/8
|
||||
final byte SECTION_1 = 0x0A;
|
||||
// 172.16.x.x/12
|
||||
final byte SECTION_2 = (byte) 0xAC;
|
||||
final byte SECTION_3 = (byte) 0x10;
|
||||
final byte SECTION_4 = (byte) 0x1F;
|
||||
// 192.168.x.x/16
|
||||
final byte SECTION_5 = (byte) 0xC0;
|
||||
final byte SECTION_6 = (byte) 0xA8;
|
||||
switch (b0)
|
||||
{
|
||||
case SECTION_1:
|
||||
return true;
|
||||
case SECTION_2:
|
||||
if (b1 >= SECTION_3 && b1 <= SECTION_4)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
case SECTION_5:
|
||||
switch (b1)
|
||||
{
|
||||
case SECTION_6:
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将IPv4地址转换成字节
|
||||
*
|
||||
* @param text IPv4地址
|
||||
* @return byte 字节
|
||||
*/
|
||||
public static byte[] textToNumericFormatV4(String text)
|
||||
{
|
||||
if (text.length() == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
byte[] bytes = new byte[4];
|
||||
String[] elements = text.split("\\.", -1);
|
||||
try
|
||||
{
|
||||
long l;
|
||||
int i;
|
||||
switch (elements.length)
|
||||
{
|
||||
case 1:
|
||||
l = Long.parseLong(elements[0]);
|
||||
if ((l < 0L) || (l > 4294967295L))
|
||||
return null;
|
||||
bytes[0] = (byte) (int) (l >> 24 & 0xFF);
|
||||
bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
|
||||
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
|
||||
bytes[3] = (byte) (int) (l & 0xFF);
|
||||
break;
|
||||
case 2:
|
||||
l = Integer.parseInt(elements[0]);
|
||||
if ((l < 0L) || (l > 255L))
|
||||
return null;
|
||||
bytes[0] = (byte) (int) (l & 0xFF);
|
||||
l = Integer.parseInt(elements[1]);
|
||||
if ((l < 0L) || (l > 16777215L))
|
||||
return null;
|
||||
bytes[1] = (byte) (int) (l >> 16 & 0xFF);
|
||||
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
|
||||
bytes[3] = (byte) (int) (l & 0xFF);
|
||||
break;
|
||||
case 3:
|
||||
for (i = 0; i < 2; ++i)
|
||||
{
|
||||
l = Integer.parseInt(elements[i]);
|
||||
if ((l < 0L) || (l > 255L))
|
||||
return null;
|
||||
bytes[i] = (byte) (int) (l & 0xFF);
|
||||
}
|
||||
l = Integer.parseInt(elements[2]);
|
||||
if ((l < 0L) || (l > 65535L))
|
||||
return null;
|
||||
bytes[2] = (byte) (int) (l >> 8 & 0xFF);
|
||||
bytes[3] = (byte) (int) (l & 0xFF);
|
||||
break;
|
||||
case 4:
|
||||
for (i = 0; i < 4; ++i)
|
||||
{
|
||||
l = Integer.parseInt(elements[i]);
|
||||
if ((l < 0L) || (l > 255L))
|
||||
return null;
|
||||
bytes[i] = (byte) (int) (l & 0xFF);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
catch (NumberFormatException e)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public static String getHostIp()
|
||||
{
|
||||
try
|
||||
{
|
||||
return InetAddress.getLocalHost().getHostAddress();
|
||||
}
|
||||
catch (UnknownHostException e)
|
||||
{
|
||||
}
|
||||
return "127.0.0.1";
|
||||
}
|
||||
|
||||
public static String getHostName()
|
||||
{
|
||||
try
|
||||
{
|
||||
return InetAddress.getLocalHost().getHostName();
|
||||
}
|
||||
catch (UnknownHostException e)
|
||||
{
|
||||
}
|
||||
return "未知";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,131 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
@Slf4j
|
||||
public class MD5Utils {
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @description MD5加密方法
|
||||
* @param str
|
||||
* 需要加密的字符串
|
||||
* @return 返回加密后的字符串
|
||||
*/
|
||||
public static String getMD5Str(String str)
|
||||
{
|
||||
MessageDigest messageDigest = null;
|
||||
// 加密前的准备
|
||||
try
|
||||
{
|
||||
messageDigest = MessageDigest.getInstance("MD5");
|
||||
messageDigest.reset();
|
||||
messageDigest.update(str.getBytes("UTF-8"));
|
||||
}
|
||||
catch (NoSuchAlgorithmException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
//初始化加密类失败,返回null。
|
||||
return null;
|
||||
}
|
||||
catch (UnsupportedEncodingException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
//初始化加密类失败,返回null。
|
||||
return null;
|
||||
}
|
||||
byte[] byteArray = messageDigest.digest();
|
||||
// 加密后的字符串
|
||||
StringBuffer md5StrBuff = new StringBuffer();
|
||||
for (int i = 0; i < byteArray.length; i++)
|
||||
{
|
||||
if(Integer.toHexString(0xFF & byteArray[i]).length() == 1){
|
||||
md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
|
||||
}
|
||||
else{
|
||||
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
|
||||
}
|
||||
}
|
||||
return md5StrBuff.toString();
|
||||
}
|
||||
|
||||
public static String md5Str(String str) {
|
||||
MessageDigest messageDigest = null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
messageDigest = MessageDigest.getInstance("MD5");
|
||||
messageDigest.reset();
|
||||
messageDigest.update(str.getBytes("UTF-8"));
|
||||
}catch (Exception e) {
|
||||
return str;
|
||||
}
|
||||
byte[] byteArray = messageDigest.digest();
|
||||
StringBuffer md5StrBuff = new StringBuffer();
|
||||
for (int i = 0; i < byteArray.length; i++) {
|
||||
if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
|
||||
md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
|
||||
else
|
||||
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
|
||||
}
|
||||
return md5StrBuff.toString().toUpperCase();
|
||||
}
|
||||
|
||||
|
||||
private static byte[] md5(String s)
|
||||
{
|
||||
MessageDigest algorithm;
|
||||
try
|
||||
{
|
||||
algorithm = MessageDigest.getInstance("MD5");
|
||||
algorithm.reset();
|
||||
algorithm.update(s.getBytes("UTF-8"));
|
||||
byte[] messageDigest = algorithm.digest();
|
||||
return messageDigest;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("MD5 Error...", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static final String toHex(byte hash[])
|
||||
{
|
||||
if (hash == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
StringBuffer buf = new StringBuffer(hash.length * 2);
|
||||
int i;
|
||||
|
||||
for (i = 0; i < hash.length; i++)
|
||||
{
|
||||
if ((hash[i] & 0xff) < 0x10)
|
||||
{
|
||||
buf.append("0");
|
||||
}
|
||||
buf.append(Long.toString(hash[i] & 0xff, 16));
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public static String hash(String s)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("not supported charset...{}", e);
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author benny
|
||||
* @Description TODO:媒体类型工具类
|
||||
* @date 2019-05-28
|
||||
*/
|
||||
public class MimeTypeUtils
|
||||
{
|
||||
public static final String IMAGE_PNG = "image/png";
|
||||
|
||||
public static final String IMAGE_JPG = "image/jpg";
|
||||
|
||||
public static final String IMAGE_JPEG = "image/jpeg";
|
||||
|
||||
public static final String IMAGE_BMP = "image/bmp";
|
||||
|
||||
public static final String IMAGE_GIF = "image/gif";
|
||||
|
||||
public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" };
|
||||
|
||||
public static final String[] FLASH_EXTENSION = { "swf", "flv" };
|
||||
|
||||
public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
|
||||
"asf", "rm", "rmvb" ,"mp4", "ogg"};
|
||||
|
||||
public static final String[] DEFAULT_ALLOWED_EXTENSION = {
|
||||
// 图片
|
||||
"bmp", "gif", "jpg", "jpeg", "png",
|
||||
// word excel powerpoint
|
||||
"doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
|
||||
// 压缩文件
|
||||
"rar", "zip", "gz", "bz2",
|
||||
// pdf
|
||||
"pdf" };
|
||||
|
||||
public static String getExtension(String prefix)
|
||||
{
|
||||
switch (prefix)
|
||||
{
|
||||
case IMAGE_PNG:
|
||||
return "png";
|
||||
case IMAGE_JPG:
|
||||
return "jpg";
|
||||
case IMAGE_JPEG:
|
||||
return "jpeg";
|
||||
case IMAGE_BMP:
|
||||
return "bmp";
|
||||
case IMAGE_GIF:
|
||||
return "gif";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package net.shapelight.common.utils;
|
||||
import java.io.IOException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.InvalidKeyException;
|
||||
|
||||
import org.xmlpull.v1.XmlPullParserException;
|
||||
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.errors.MinioException;
|
||||
public class MinIOTest {
|
||||
public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InvalidKeyException, XmlPullParserException {
|
||||
try {
|
||||
// Create a minioClient with the MinIO Server name, Port, Access key and Secret key.
|
||||
MinioClient minioClient = new MinioClient("http://192.168.1.111:9000", "minioadmin", "minioadmin");
|
||||
|
||||
// Check if the bucket already exists.
|
||||
boolean isExist =
|
||||
minioClient.bucketExists("face");
|
||||
//minioClient.bucketExists(BucketExistsArgs.builder().bucket("asiatrip").build());
|
||||
if(isExist) {
|
||||
System.out.println("Bucket already exists.");
|
||||
} else {
|
||||
// Make a new bucket called asiatrip to hold a zip file of photos.
|
||||
//minioClient.makeBucket(MakeBucketArgs.builder().bucket("asiatrip").build());
|
||||
minioClient.makeBucket("face");
|
||||
}
|
||||
|
||||
// Upload the zip file to the bucket with putObject
|
||||
minioClient.putObject("face","232/1.jpg", "D:\\project\\cell\\1.jpg", null);
|
||||
String url = minioClient.getObjectUrl("face", "232/1.jpg"); //文件访问路径
|
||||
System.out.println(url);
|
||||
System.out.println("/home/user/Photos/asiaphotos.zip is successfully uploaded as asiaphotos.zip to `asiatrip` bucket.");
|
||||
} catch(MinioException e) {
|
||||
System.out.println("Error occurred: " + e);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,239 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.PutObjectOptions;
|
||||
import io.minio.errors.InvalidEndpointException;
|
||||
import io.minio.errors.InvalidPortException;
|
||||
//import io.minio.policy.PolicyType;
|
||||
import net.shapelight.common.config.GlobalValue;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.imageio.ImageIO;
|
||||
import java.io.InputStream;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* 对象存储工具类
|
||||
*/
|
||||
//@Component
|
||||
public class MinioUtil {
|
||||
|
||||
// private static MinioUtil minioUtil;
|
||||
//
|
||||
// @Autowired
|
||||
// private GlobalValue globalValue;
|
||||
//
|
||||
// //Mino服务器的AccessKey
|
||||
// private final transient static String ACCESS_KEY = "7885444af42e4b30c518c5be17c8850b";
|
||||
// //Mino服务器的SecretKey
|
||||
// private final transient static String SECRET_KEY = "0fad3477fb9f60c7be75561db967e8d7";
|
||||
// //Mino服务器的AccessKey
|
||||
//// private final transient static String ACCESS_KEY = "11f6a78ee6922";
|
||||
//// //Mino服务器的SecretKey
|
||||
//// private final transient static String SECRET_KEY = "MjkzODM4Mzc2NTMyNjIzOTg3NTI5MDMwMzU3NjMwOTc2MDA";
|
||||
// //桶名称:wq
|
||||
// private final transient static String BUCKET_NAME = "cell";
|
||||
// //读写分离-上传服务器
|
||||
// private final transient static String OSS_URL_WRITE = "https://c.shapelight.net";
|
||||
// //读写分离-下载服务器
|
||||
// private final transient static String OOS_URL_READ = "https://c.shapelight.net";
|
||||
// //minio服务端口,默认是9000
|
||||
// private final transient static int OSS_PORT = 19000;
|
||||
// private transient static boolean BUCKET_EXISTS = false;
|
||||
//
|
||||
//
|
||||
// public void setGlobalValue(GlobalValue globalValue) {
|
||||
// this.globalValue = globalValue;
|
||||
// }
|
||||
//
|
||||
// @PostConstruct
|
||||
// public void init(){
|
||||
// minioUtil = this;
|
||||
// minioUtil.globalValue = this.globalValue;
|
||||
// }
|
||||
//
|
||||
// public static String getBucketName(){
|
||||
// return BUCKET_NAME;
|
||||
// }
|
||||
//
|
||||
// //单例模式-内部类实现
|
||||
// private static class MinioClientHolder {
|
||||
// private static MinioClient minioClient;
|
||||
// static {
|
||||
// try {
|
||||
//// minioClient =
|
||||
//// new MinioClient(
|
||||
//// globalValue.getMinioEndpoint(),
|
||||
//// globalValue.getMinioAccessKey(),
|
||||
//// globalValue.getMinioSecretKey());
|
||||
//
|
||||
// minioClient = new MinioClient(OSS_URL_WRITE, OSS_PORT, ACCESS_KEY, SECRET_KEY);
|
||||
// if (!minioClient.bucketExists(BUCKET_NAME)) {
|
||||
// minioClient.makeBucket(BUCKET_NAME);
|
||||
// }
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 获取minio客户端实例
|
||||
// *
|
||||
// * @return
|
||||
// */
|
||||
// public static MinioClient getMinioClient() {
|
||||
// return MinioClientHolder.minioClient;
|
||||
// }
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// private static final Logger log = LoggerFactory.getLogger(MinioUtil.class);
|
||||
// //Mino服务器的AccessKey
|
||||
// private final transient static String ACCESS_KEY = "admin";
|
||||
// //Mino服务器的SecretKey
|
||||
// private final transient static String SECRET_KEY = "admin@C501";
|
||||
// //桶名称
|
||||
// private final transient static String BUCKET_NAME = "cell";
|
||||
// //读写分离-上传服务器
|
||||
// private final transient static String OSS_URL_WRITE = "http://192.168.1.111";
|
||||
// //读写分离-下载服务器
|
||||
// private final transient static String OOS_URL_READ = "http://192.168.1.111";
|
||||
// //minio服务端口,默认是9000
|
||||
// private final transient static int OSS_PORT = 9000;
|
||||
// private transient static boolean BUCKET_EXISTS = false;
|
||||
//
|
||||
// //单例模式-内部类实现
|
||||
// private static class MinioClientHolder {
|
||||
// private static MinioClient minioClient;
|
||||
//
|
||||
// static {
|
||||
// try {
|
||||
// minioClient = new MinioClient(OSS_URL_WRITE, OSS_PORT, ACCESS_KEY, SECRET_KEY);
|
||||
// } catch (InvalidEndpointException e) {
|
||||
// e.printStackTrace();
|
||||
// } catch (InvalidPortException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 获取minio客户端实例
|
||||
// *
|
||||
// * @return
|
||||
// */
|
||||
// private static MinioClient getMinioClient() {
|
||||
// return MinioClientHolder.minioClient;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 上传文件
|
||||
// * 支持单文件,多文件
|
||||
// * 返回文件访问路径,多文件以分号‘;’分隔
|
||||
// *
|
||||
// * @param muFiles
|
||||
// * @return
|
||||
// */
|
||||
// public static String uploadFiles(MultipartFile... muFiles) {
|
||||
// if (muFiles.length < 1) {
|
||||
// throw new RuntimeException("上传文件为空!");
|
||||
// }
|
||||
// StringBuilder str = new StringBuilder();
|
||||
// for (MultipartFile muFile : muFiles) {
|
||||
// str.append(uploadFile(muFile));
|
||||
// str.append(";");
|
||||
// }
|
||||
// return str.deleteCharAt(str.length() - 1).toString();
|
||||
//
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 内部方法
|
||||
// * 上传文件
|
||||
// *
|
||||
// * @param muFile
|
||||
// * @return
|
||||
// */
|
||||
// private static String uploadFile(MultipartFile muFile) {
|
||||
// String fileName = getFilePathName(muFile, false);
|
||||
// try {
|
||||
// MinioClient minioClient = getMinioClient();
|
||||
// if (!BUCKET_EXISTS && !minioClient.bucketExists(BUCKET_NAME)) {
|
||||
// minioClient.makeBucket(BUCKET_NAME);
|
||||
// //minioClient.setBucketPolicy(BUCKET_NAME, "", PolicyType.READ_ONLY);
|
||||
// BUCKET_EXISTS = true;
|
||||
// }
|
||||
// InputStream inputStream = muFile.getInputStream();
|
||||
//// 如果是图片文件就进行压缩
|
||||
//// if (ImageUtil.isImage(muFile.getOriginalFilename())){
|
||||
//// inputStream=ImageUtil.getInputStream(
|
||||
//// ImageUtil.setWatermark(
|
||||
//// ImageUtil.compress(
|
||||
//// ImageIO.read(inputStream))),
|
||||
//// ImageUtil.getFileExtention(muFile.getOriginalFilename()));
|
||||
//// }
|
||||
//// minioClient.putObject(BUCKET_NAME, fileName , inputStream, muFile.getContentType());
|
||||
// minioClient.putObject(BUCKET_NAME, fileName, inputStream, new PutObjectOptions(inputStream.available(), -1));
|
||||
// inputStream.close();
|
||||
// } catch (Exception e) {
|
||||
// log.error("文件上传失败", e);
|
||||
// throw new RuntimeException("文件上传失败");
|
||||
// }
|
||||
// return OOS_URL_READ + BUCKET_NAME + fileName;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 获取文件名
|
||||
// *
|
||||
// * @param muFile 文件
|
||||
// * @param isRetain 是否保留源文件名
|
||||
// * @return 返回文件名,以当前年月日作为前缀路径
|
||||
// */
|
||||
// private static String getFilePathName(MultipartFile muFile, boolean isRetain) {
|
||||
// String fileName = muFile.getOriginalFilename();
|
||||
// String name = fileName;
|
||||
// String prefix = "";
|
||||
// if (fileName.indexOf('.') != -1) {
|
||||
// name = fileName.substring(0, fileName.indexOf('.'));
|
||||
// prefix = fileName.substring(fileName.lastIndexOf("."));
|
||||
// }
|
||||
//
|
||||
// LocalDate date = LocalDate.now();
|
||||
// StringBuilder filePathName = new StringBuilder("/upload/");
|
||||
// filePathName.append(date.getYear());
|
||||
// filePathName.append("/");
|
||||
// filePathName.append(date.getMonthValue());
|
||||
// filePathName.append("/");
|
||||
// filePathName.append(date.getDayOfMonth());
|
||||
// filePathName.append("/");
|
||||
// //添加随机后缀
|
||||
// Random r = new Random();
|
||||
// int pix = r.ints(1, (100 + 1)).findFirst().getAsInt();
|
||||
// filePathName.append(System.currentTimeMillis());
|
||||
// filePathName.append("" + pix);
|
||||
// //文件名超过32字符则截取
|
||||
// if (isRetain) {
|
||||
// filePathName.append("_");
|
||||
// if (name.length() >= 32) {
|
||||
// name = name.substring(0, 32);
|
||||
// }
|
||||
// filePathName.append(name);
|
||||
// }
|
||||
// filePathName.append(prefix);
|
||||
// return filePathName.toString();
|
||||
// }
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class MyBeanUtils {
|
||||
/**
|
||||
* @param orig 源对象
|
||||
* @param dest 目标对象
|
||||
*/
|
||||
public static void copyProperties(final Object orig,final Object dest){
|
||||
try{
|
||||
org.apache.commons.beanutils.BeanUtils.copyProperties(dest, orig);
|
||||
}catch (Exception e){
|
||||
throw new RuntimeException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @Description:拷贝list元素对象,将origs中的元素信息,拷贝覆盖至dests中
|
||||
* @param origs 源list对象
|
||||
* @param dests 目标list对象
|
||||
* @param origsElementTpe 源list元素类型对象
|
||||
* @param destElementTpe 目标list元素类型对象
|
||||
* @param <T1> 源list元素类型
|
||||
* @param <T2> 目标list元素类型
|
||||
*/
|
||||
public static <T1,T2> void copyProperties(final List<T1> origs, final List<T2> dests, Class<T1> origsElementTpe, Class<T2> destElementTpe){
|
||||
if(origs==null||dests==null){
|
||||
return ;
|
||||
}
|
||||
if(dests.size()!=0){
|
||||
//防止目标对象被覆盖,要求必须长度为零
|
||||
throw new RuntimeException("目标对象存在值");
|
||||
}
|
||||
try{
|
||||
for (T1 orig: origs) {
|
||||
T2 t = destElementTpe.newInstance();
|
||||
dests.add(t);
|
||||
copyProperties(orig,t);
|
||||
}
|
||||
}catch (Exception e){
|
||||
throw new RuntimeException(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import java.sql.Time;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class MyDateUtils {
|
||||
|
||||
public static String getCurrentDayStartTime(){
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
Date mondayDate = cal.getTime();
|
||||
String weekBegin = sdf.format(mondayDate)+" 00:00:00";
|
||||
return weekBegin;
|
||||
}
|
||||
|
||||
public static String getCurrentDayEndTime(){
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
Date mondayDate = cal.getTime();
|
||||
String weekBegin = sdf.format(mondayDate)+" 23:59:59";
|
||||
return weekBegin;
|
||||
}
|
||||
|
||||
public static String getCurrentWeekStartTime(){
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
//设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
|
||||
cal.setFirstDayOfWeek(Calendar.MONDAY);
|
||||
//获得当前日期是一个星期的第几天
|
||||
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
|
||||
if(dayWeek==1){
|
||||
dayWeek = 8;
|
||||
}
|
||||
|
||||
// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
|
||||
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);
|
||||
Date mondayDate = cal.getTime();
|
||||
String weekBegin = sdf.format(mondayDate)+" 00:00:00";
|
||||
return weekBegin;
|
||||
}
|
||||
|
||||
public static String getCurrentWeekEndTime(){
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Calendar cal = Calendar.getInstance();
|
||||
//设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
|
||||
cal.setFirstDayOfWeek(Calendar.MONDAY);
|
||||
//获得当前日期是一个星期的第几天
|
||||
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
|
||||
if(dayWeek==1){
|
||||
dayWeek = 8;
|
||||
}
|
||||
cal.add(Calendar.DATE, 4 +cal.getFirstDayOfWeek());
|
||||
Date sundayDate = cal.getTime();
|
||||
String weekEnd = sdf.format(sundayDate)+" 23:59:59";
|
||||
return weekEnd;
|
||||
}
|
||||
|
||||
public static String getCurrentMonthStartTime(){
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(new Date());
|
||||
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
|
||||
return sdf.format(calendar.getTime())+" 00:00:00";
|
||||
}
|
||||
|
||||
public static String getCurrentMonthEndTime(){
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Calendar calendar2 = Calendar.getInstance();
|
||||
calendar2.setTime(new Date());
|
||||
calendar2.set(Calendar.DAY_OF_MONTH, calendar2.getActualMaximum(Calendar.DAY_OF_MONTH));
|
||||
return sdf.format(calendar2.getTime())+" 23:59:59";
|
||||
}
|
||||
|
||||
public static int getSeconds(Time time){
|
||||
int sec = time.getHours() * 3600 + time.getMinutes()*60 + time.getSeconds();
|
||||
return sec;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
|
||||
|
||||
/**
|
||||
* 日志辅助类,用来处理敏感信息,进行脱敏
|
||||
* @author tyg
|
||||
* @date 2018年5月5日下午4:01:22
|
||||
*/
|
||||
public class PrivacyUtil {
|
||||
|
||||
private static String desensitizedName(String fullName) {
|
||||
if (!Strings.isNullOrEmpty(fullName)) {
|
||||
String name = StringUtils.left(fullName, 1);
|
||||
return StringUtils.rightPad(name, StringUtils.length(fullName), "*");
|
||||
}
|
||||
return fullName;
|
||||
}
|
||||
|
||||
private static String desensitizedPhoneNumber(String phoneNumber) {
|
||||
if (StringUtils.isNotEmpty(phoneNumber)) {
|
||||
phoneNumber = phoneNumber.replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2");
|
||||
}
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
|
||||
private static String desensitizedIdNumber(String idNumber) {
|
||||
if (!Strings.isNullOrEmpty(idNumber)) {
|
||||
if (idNumber.length() == 15) {
|
||||
idNumber = idNumber.replaceAll("(\\w{6})\\w*(\\w{4})", "$1******$2");
|
||||
}
|
||||
if (idNumber.length() == 18) {
|
||||
idNumber = idNumber.replaceAll("(\\w{6})\\w*(\\w{4})", "$1*********$2");
|
||||
}
|
||||
}
|
||||
return idNumber;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String id = "610124198825458";
|
||||
String ide = desensitizedIdNumber(id);
|
||||
System.out.println(ide);
|
||||
|
||||
String m = "1368898";
|
||||
String me = desensitizedPhoneNumber(m);
|
||||
System.out.println(me);
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
|
||||
|
||||
package net.shapelight.common.utils;
|
||||
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.core.metadata.OrderItem;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import net.shapelight.common.xss.SQLFilter;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 查询参数
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class Query<T> {
|
||||
|
||||
public IPage<T> getPage(Map<String, Object> params) {
|
||||
return this.getPage(params, null, false);
|
||||
}
|
||||
|
||||
public IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
|
||||
//分页参数
|
||||
long curPage = 1;
|
||||
long limit = 10;
|
||||
|
||||
if(params.get(Constant.PAGE) != null){
|
||||
curPage = Long.parseLong((String)params.get(Constant.PAGE));
|
||||
}
|
||||
if(params.get(Constant.LIMIT) != null){
|
||||
limit = Long.parseLong((String)params.get(Constant.LIMIT));
|
||||
}
|
||||
|
||||
//分页对象
|
||||
Page<T> page = new Page<>(curPage, limit);
|
||||
|
||||
//分页参数
|
||||
params.put(Constant.PAGE, page);
|
||||
|
||||
//排序字段
|
||||
//防止SQL注入(因为sidx、order是通过拼接SQL实现排序的,会有SQL注入风险)
|
||||
String orderField = SQLFilter.sqlInject((String)params.get(Constant.ORDER_FIELD));
|
||||
String order = (String)params.get(Constant.ORDER);
|
||||
|
||||
//前端字段排序
|
||||
if(StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)){
|
||||
if(Constant.ASC.equalsIgnoreCase(order)) {
|
||||
return page.addOrder(OrderItem.asc(orderField));
|
||||
}else {
|
||||
return page.addOrder(OrderItem.desc(orderField));
|
||||
}
|
||||
}
|
||||
|
||||
//没有排序字段,则不排序
|
||||
if(StringUtils.isBlank(defaultOrderField)){
|
||||
return page;
|
||||
}
|
||||
|
||||
//默认排序
|
||||
if(isAsc) {
|
||||
page.addOrder(OrderItem.asc(defaultOrderField));
|
||||
}else {
|
||||
page.addOrder(OrderItem.desc(defaultOrderField));
|
||||
}
|
||||
|
||||
return page;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
|
||||
|
||||
package net.shapelight.common.utils;
|
||||
|
||||
/**
|
||||
* Redis所有Keys
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class RedisKeys {
|
||||
|
||||
public static String getSysConfigKey(String key){
|
||||
return "sys:config:" + key;
|
||||
}
|
||||
|
||||
public static String getShiroSessionKey(String key){
|
||||
return "sessionid:" + key;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,365 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.client.ResponseErrorHandler;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Created by huangquanwei on 2019/5/31 15:58
|
||||
* restTemplateUtils 高性能请求http https
|
||||
*
|
||||
*/
|
||||
@Slf4j
|
||||
public class RestTemplateUtils {
|
||||
|
||||
/**
|
||||
* http 请求 GET
|
||||
* @param url 地址
|
||||
* @param params 参数
|
||||
* @param connecTimeout 连接时间 180000
|
||||
* @param readTimeout 读取时间 180000
|
||||
* @param retryCount 重试机制
|
||||
* @return String 类型
|
||||
*/
|
||||
public static String getHttp(String url, JSONObject params,int connecTimeout,int readTimeout ,int retryCount) {
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
|
||||
requestFactory.setConnectTimeout(connecTimeout);
|
||||
requestFactory.setReadTimeout(readTimeout);
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
|
||||
restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); // 异常处理
|
||||
url = expandURL(url, params.keySet());
|
||||
String result = null; // 返回值类型;
|
||||
for (int i = 1; i <= retryCount; i++){
|
||||
try {
|
||||
result = restTemplate.getForObject(url, String.class, params);
|
||||
return result;
|
||||
} catch (RestClientException e) {
|
||||
System.out.println("-----------开始-----------重试count: "+i);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* https 请求 GET
|
||||
* @param url 地址
|
||||
* @param params 参数
|
||||
* @param connecTimeout 连接时间
|
||||
* @param readTimeout 读取时间
|
||||
* @param retryCount 重试机制
|
||||
* @return String 类型
|
||||
*/
|
||||
public static String getHttps(String url, JSONObject params,int connecTimeout,int readTimeout ,int retryCount) {
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
|
||||
requestFactory.setConnectTimeout(connecTimeout);
|
||||
requestFactory.setReadTimeout(readTimeout);
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
|
||||
restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); //error处理
|
||||
restTemplate.setRequestFactory(new HttpsClientRequestFactory()); // 绕过https
|
||||
url = expandURL(url, params.keySet());
|
||||
String result = null; // 返回值类型;
|
||||
for (int i = 1; i <= retryCount; i++){
|
||||
try {
|
||||
result = restTemplate.getForObject(url, String.class, params);
|
||||
return result;
|
||||
} catch (RestClientException e) {
|
||||
System.out.println("-----------开始-----------重试count: "+i);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* http 请求 post
|
||||
* @param url 地址
|
||||
* @param params 参数
|
||||
* @param headersMap header
|
||||
* @param connecTimeout 连接时间
|
||||
* @param readTimeout 读取时间
|
||||
* @param retryCount 重试机制
|
||||
* @return String 类型
|
||||
*/
|
||||
public static String postHttp(String url, JSONObject params, Map headersMap,int connecTimeout,int readTimeout,int retryCount) {
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); // 时间函数
|
||||
requestFactory.setConnectTimeout(connecTimeout);
|
||||
requestFactory.setReadTimeout(readTimeout);
|
||||
//内部实际实现为 HttpClient
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
|
||||
restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); // 异常处理的headers error 处理
|
||||
// 设置·header信息
|
||||
HttpHeaders requestHeaders = new HttpHeaders();
|
||||
requestHeaders.setAll(headersMap);
|
||||
HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(params, requestHeaders); // josn utf-8 格式
|
||||
String result = null; // 返回值类型;
|
||||
for (int i = 1; i <= retryCount; i++){
|
||||
try {
|
||||
result = restTemplate.postForObject(url, requestEntity, String.class);
|
||||
return result;
|
||||
} catch (RestClientException e) {
|
||||
System.out.println("-----------开始-----------重试count: "+i);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
public static String postHttp(String url, JSONObject params) {
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); // 时间函数
|
||||
requestFactory.setConnectTimeout(180000);
|
||||
requestFactory.setReadTimeout(180000);
|
||||
//内部实际实现为 HttpClient
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
|
||||
restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); // 异常处理的headers error 处理
|
||||
// 设置·header信息
|
||||
HttpHeaders requestHeaders = new HttpHeaders();
|
||||
requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
|
||||
//requestHeaders.setAll(headersMap);
|
||||
HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(params, requestHeaders); // josn utf-8 格式
|
||||
String result = null; // 返回值类型;
|
||||
for (int i = 1; i <= 3; i++){
|
||||
try {
|
||||
result = restTemplate.postForObject(url, requestEntity, String.class);
|
||||
return result;
|
||||
} catch (RestClientException e) {
|
||||
System.out.println("-----------开始-----------重试count: "+i);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 加密参数类型请求 application/x-www-form-urlencoded
|
||||
* MultiValueMap<String, Object>
|
||||
* 采用 HttpEntity<MultiValueMap<String, Object>> 构造
|
||||
* http 请求 post
|
||||
* @param url 地址
|
||||
* @param
|
||||
* @param headersMap header
|
||||
* @param connecTimeout 连接时间
|
||||
* @param readTimeout 读取时间
|
||||
* @param retryCount 重试机制
|
||||
* @return String 类型
|
||||
*/
|
||||
public static String postHttpEncryption(String url, MultiValueMap<String, Object> postParameters, Map headersMap, int connecTimeout, int readTimeout, int retryCount) {
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); // 时间函数
|
||||
requestFactory.setConnectTimeout(connecTimeout);
|
||||
requestFactory.setReadTimeout(readTimeout);
|
||||
//内部实际实现为 HttpClient
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
|
||||
restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); // 异常处理的headers error 处理
|
||||
// 设置·header信息
|
||||
HttpHeaders requestHeaders = new HttpHeaders();
|
||||
requestHeaders.setAll(headersMap);
|
||||
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(postParameters, requestHeaders);
|
||||
String result = null; // 返回值类型;
|
||||
for (int i = 1; i <= retryCount; i++){
|
||||
try {
|
||||
result = restTemplate.postForObject(url, requestEntity, String.class);
|
||||
return result;
|
||||
} catch (RestClientException e) {
|
||||
System.out.println("-----------开始-----------重试count: "+i);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param url 请求地址
|
||||
* @param params 请求 josn 格式参数
|
||||
* @param headersMap headers 头部需要参数
|
||||
* @param retryCount 重试机制
|
||||
* @return 返回string类型返回值
|
||||
* 参数json方法传递
|
||||
*/
|
||||
public static String postHttps(String url, JSONObject params, Map headersMap,int connecTimeout,int readTimeout,int retryCount) {
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); // 时间函数
|
||||
requestFactory.setConnectTimeout(connecTimeout);
|
||||
requestFactory.setReadTimeout(readTimeout);
|
||||
//内部实际实现为 HttpClient
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
|
||||
restTemplate.setRequestFactory(new HttpsClientRequestFactory()); // 绕过https
|
||||
restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); // 异常处理的headers error 处理
|
||||
// 设置·header信息
|
||||
HttpHeaders requestHeaders = new HttpHeaders();
|
||||
requestHeaders.setAll(headersMap);
|
||||
HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(params, requestHeaders); // josn utf-8 格式
|
||||
String result = null; // 返回值类型;
|
||||
for (int i = 1; i <= retryCount; i++){
|
||||
try {
|
||||
result = restTemplate.postForObject(url, requestEntity, String.class);
|
||||
return result;
|
||||
} catch (RestClientException e) {
|
||||
System.out.println("-----------开始-----------重试count: "+i);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* http 请求 post
|
||||
*
|
||||
* @param url 地址
|
||||
* @param params 参数
|
||||
* @param headersMap header
|
||||
* @param connecTimeout 连接时间
|
||||
* @param readTimeout 读取时间
|
||||
* @param retryCount 重试机制
|
||||
* @return String 类型
|
||||
* 参数是以普通的post参数传递,非json传递参数
|
||||
*/
|
||||
public static String commonPostHttp(String url, Map params, Map headersMap, int connecTimeout, int readTimeout, int retryCount) {
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); // 时间函数
|
||||
requestFactory.setConnectTimeout(connecTimeout);
|
||||
requestFactory.setReadTimeout(readTimeout);
|
||||
//内部实际实现为 HttpClient
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 设置编码集
|
||||
restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); // 异常处理的headers error 处理
|
||||
// 设置·header信息
|
||||
HttpHeaders requestHeaders = new HttpHeaders();
|
||||
requestHeaders.setAll(headersMap);
|
||||
|
||||
HttpEntity<Map> requestEntity = new HttpEntity<Map>(params, requestHeaders); // josn utf-8 格式
|
||||
String result = null; // 返回值类型;
|
||||
for (int i = 1; i <= retryCount; i++) {
|
||||
try {
|
||||
result = restTemplate.postForObject(url, requestEntity, String.class);
|
||||
return result;
|
||||
} catch (RestClientException e) {
|
||||
log.error("-----------开始-----------重试count: " + i);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static MultiValueMap<String, String> createMultiValueMap(JSONObject params) {
|
||||
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
|
||||
for (String key : params.keySet()) {
|
||||
if (params.get(key) instanceof List) {
|
||||
for (Iterator<String> it = ((List<String>) params.get(key)).iterator(); it.hasNext(); ) {
|
||||
String value = it.next();
|
||||
map.add(key, value);
|
||||
}
|
||||
} else {
|
||||
map.add(key, params.getString(key));
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param url
|
||||
* @param keys
|
||||
* @return
|
||||
* @Title: expandURL
|
||||
* @author:
|
||||
* @Description: TODO
|
||||
* @return: String
|
||||
*/
|
||||
private static String expandURL(String url, Set<?> keys) {
|
||||
final Pattern QUERY_PARAM_PATTERN = Pattern.compile("([^&=]+)(=?)([^&]+)?");
|
||||
Matcher mc = QUERY_PARAM_PATTERN.matcher(url);
|
||||
StringBuilder sb = new StringBuilder(url);
|
||||
if (mc.find()) {
|
||||
sb.append("&");
|
||||
} else {
|
||||
sb.append("?");
|
||||
}
|
||||
|
||||
for (Object key : keys) {
|
||||
sb.append(key).append("=").append("{").append(key).append("}").append("&");
|
||||
}
|
||||
return sb.deleteCharAt(sb.length() - 1).toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @ClassName: DefaultResponseErrorHandler
|
||||
* @Description: TODO
|
||||
* @author:
|
||||
* @date: 2
|
||||
*/
|
||||
private static class DefaultResponseErrorHandler implements ResponseErrorHandler {
|
||||
|
||||
/** 对response进行判断,如果是异常情况,返回true */
|
||||
@Override
|
||||
public boolean hasError(ClientHttpResponse response) throws IOException {
|
||||
return response.getStatusCode().value() != HttpServletResponse.SC_OK;
|
||||
}
|
||||
|
||||
/** 异常情况时的处理方法 */
|
||||
@Override
|
||||
public void handleError(ClientHttpResponse response) throws IOException {
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(response.getBody()));
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String str = null;
|
||||
while ((str = br.readLine()) != null) {
|
||||
sb.append(str);
|
||||
}
|
||||
try {
|
||||
throw new Exception(sb.toString());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String args[]){
|
||||
Map<String, Object> ser = new HashMap();
|
||||
//QteTZKu44E5PQY5ZESR4cMR2Qh9iHUZr
|
||||
//NG0mV1kpuY9WQ7PryPME5Tcz85JtwTHZ
|
||||
//ser.put("serial","QteTZKu44E5PQY5ZESR4cMR2Qh9iHUZr");
|
||||
//ser.put("serial","NG0mV1kpuY9WQ7PryPME5Tcz85JtwTHZ");
|
||||
|
||||
JSONObject req = new JSONObject();
|
||||
//req.put("serial","NG0mV1kpuY9WQ7PryPME5Tcz85JtwTHZ");
|
||||
req.put("serial","MDWO4hd4aoAfOYjy7Tip5I50XZNKUYOS");
|
||||
|
||||
// req.put("serial","QteTZKu44E5PQY5ZESR4cMR2Qh9iHUZr");
|
||||
|
||||
String res = postHttp("http://39.96.9.232:3389/getSerialInfo",req);
|
||||
log.info(res);
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
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;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 客户端工具类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class ServletUtils
|
||||
{
|
||||
/**
|
||||
* 获取String参数
|
||||
*/
|
||||
public static String getParameter(String name)
|
||||
{
|
||||
return getRequest().getParameter(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取String参数
|
||||
*/
|
||||
public static String getParameter(String name, String defaultValue)
|
||||
{
|
||||
return Convert.toStr(getRequest().getParameter(name), defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Integer参数
|
||||
*/
|
||||
public static Integer getParameterToInt(String name)
|
||||
{
|
||||
return Convert.toInt(getRequest().getParameter(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Integer参数
|
||||
*/
|
||||
public static Integer getParameterToInt(String name, Integer defaultValue)
|
||||
{
|
||||
return Convert.toInt(getRequest().getParameter(name), defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取request
|
||||
*/
|
||||
public static HttpServletRequest getRequest()
|
||||
{
|
||||
return getRequestAttributes().getRequest();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取response
|
||||
*/
|
||||
public static HttpServletResponse getResponse()
|
||||
{
|
||||
return getRequestAttributes().getResponse();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取session
|
||||
*/
|
||||
public static HttpSession getSession()
|
||||
{
|
||||
return getRequest().getSession();
|
||||
}
|
||||
|
||||
public static ServletRequestAttributes getRequestAttributes()
|
||||
{
|
||||
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
|
||||
return (ServletRequestAttributes) attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字符串渲染到客户端
|
||||
*
|
||||
* @param response 渲染对象
|
||||
* @param string 待渲染的字符串
|
||||
* @return null
|
||||
*/
|
||||
public static String renderString(HttpServletResponse response, String string)
|
||||
{
|
||||
try
|
||||
{
|
||||
response.setStatus(200);
|
||||
response.setContentType("application/json");
|
||||
response.setCharacterEncoding("utf-8");
|
||||
response.getWriter().print(string);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否是Ajax异步请求
|
||||
*
|
||||
* @param request
|
||||
*/
|
||||
public static boolean isAjaxRequest(HttpServletRequest request)
|
||||
{
|
||||
String accept = request.getHeader("accept");
|
||||
if (accept != null && accept.indexOf("application/json") != -1)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
String xRequestedWith = request.getHeader("X-Requested-With");
|
||||
if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
String uri = request.getRequestURI();
|
||||
if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
String ajax = request.getParameter("__ajax");
|
||||
if (StringUtils.inStringIgnoreCase(ajax, "json", "xml"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,147 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class SnowflakeIdWorker {
|
||||
|
||||
// ==============================Fields===========================================
|
||||
/** 开始时间截 (2015-01-01) */
|
||||
private final long twepoch = 1420041600000L;
|
||||
|
||||
//private final long twepoch = 1569399429492L;
|
||||
|
||||
/** 机器id所占的位数 */
|
||||
private final long workerIdBits = 5L;
|
||||
|
||||
/** 数据标识id所占的位数 */
|
||||
private final long datacenterIdBits = 5L;
|
||||
|
||||
/** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
|
||||
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
|
||||
|
||||
/** 支持的最大数据标识id,结果是31 */
|
||||
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
|
||||
|
||||
/** 序列在id中占的位数 */
|
||||
private final long sequenceBits = 12L;
|
||||
|
||||
/** 机器ID向左移12位 */
|
||||
private final long workerIdShift = sequenceBits;
|
||||
|
||||
/** 数据标识id向左移17位(12+5) */
|
||||
private final long datacenterIdShift = sequenceBits + workerIdBits;
|
||||
|
||||
/** 时间截向左移22位(5+5+12) */
|
||||
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
|
||||
|
||||
/** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
|
||||
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
|
||||
|
||||
/** 工作机器ID(0~31) */
|
||||
private long workerId;
|
||||
|
||||
/** 数据中心ID(0~31) */
|
||||
private long datacenterId;
|
||||
|
||||
/** 毫秒内序列(0~4095) */
|
||||
private long sequence = 0L;
|
||||
|
||||
/** 上次生成ID的时间截 */
|
||||
private long lastTimestamp = -1L;
|
||||
|
||||
//==============================Constructors=====================================
|
||||
/**
|
||||
* 构造函数
|
||||
* @param workerId 工作ID (0~31)
|
||||
* @param datacenterId 数据中心ID (0~31)
|
||||
*/
|
||||
public SnowflakeIdWorker(long workerId, long datacenterId) {
|
||||
if (workerId > maxWorkerId || workerId < 0) {
|
||||
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
|
||||
}
|
||||
if (datacenterId > maxDatacenterId || datacenterId < 0) {
|
||||
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
|
||||
}
|
||||
this.workerId = workerId;
|
||||
this.datacenterId = datacenterId;
|
||||
}
|
||||
public SnowflakeIdWorker() {
|
||||
}
|
||||
|
||||
// ==============================Methods==========================================
|
||||
/**
|
||||
* 获得下一个ID (该方法是线程安全的)
|
||||
* @return SnowflakeId
|
||||
*/
|
||||
public synchronized long nextId() {
|
||||
long timestamp = timeGen();
|
||||
|
||||
//如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
|
||||
if (timestamp < lastTimestamp) {
|
||||
throw new RuntimeException(
|
||||
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
|
||||
}
|
||||
|
||||
//如果是同一时间生成的,则进行毫秒内序列
|
||||
if (lastTimestamp == timestamp) {
|
||||
sequence = (sequence + 1) & sequenceMask;
|
||||
//毫秒内序列溢出
|
||||
if (sequence == 0) {
|
||||
//阻塞到下一个毫秒,获得新的时间戳
|
||||
timestamp = tilNextMillis(lastTimestamp);
|
||||
}
|
||||
}
|
||||
//时间戳改变,毫秒内序列重置
|
||||
else {
|
||||
//sequence = 0L;
|
||||
sequence = new Random().nextInt(8);
|
||||
}
|
||||
|
||||
//上次生成ID的时间截
|
||||
lastTimestamp = timestamp;
|
||||
|
||||
//移位并通过或运算拼到一起组成64位的ID
|
||||
return ((timestamp - twepoch) << timestampLeftShift) //
|
||||
| (datacenterId << datacenterIdShift) //
|
||||
| (workerId << workerIdShift) //
|
||||
| sequence;
|
||||
}
|
||||
|
||||
/**
|
||||
* 阻塞到下一个毫秒,直到获得新的时间戳
|
||||
* @param lastTimestamp 上次生成ID的时间截
|
||||
* @return 当前时间戳
|
||||
*/
|
||||
protected long tilNextMillis(long lastTimestamp) {
|
||||
long timestamp = timeGen();
|
||||
while (timestamp <= lastTimestamp) {
|
||||
timestamp = timeGen();
|
||||
}
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回以毫秒为单位的当前时间
|
||||
* @return 当前时间(毫秒)
|
||||
*/
|
||||
protected long timeGen() {
|
||||
return System.currentTimeMillis();
|
||||
}
|
||||
|
||||
//==============================Test=============================================
|
||||
/** 测试 */
|
||||
public static void main(String[] args) {
|
||||
//SnowflakeIdWorker idWorker = new SnowflakeIdWorker(10, 10);
|
||||
|
||||
SnowflakeIdWorker idWorker = new SnowflakeIdWorker();
|
||||
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
long id = idWorker.nextId();
|
||||
//System.out.println(Long.toBinaryString(id));
|
||||
System.out.println(id);
|
||||
|
||||
}
|
||||
//System.out.println(idWorker.timeGen());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,440 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 字符串工具类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class StringUtils extends org.apache.commons.lang3.StringUtils
|
||||
{
|
||||
/** 空字符串 */
|
||||
private static final String NULLSTR = "";
|
||||
|
||||
/** 下划线 */
|
||||
private static final char SEPARATOR = '_';
|
||||
|
||||
/**
|
||||
* 获取参数不为空值
|
||||
*
|
||||
* @param value defaultValue 要判断的value
|
||||
* @return value 返回值
|
||||
*/
|
||||
public static <T> T nvl(T value, T defaultValue)
|
||||
{
|
||||
return value != null ? value : defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个Collection是否为空, 包含List,Set,Queue
|
||||
*
|
||||
* @param coll 要判断的Collection
|
||||
* @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isEmpty(Collection<?> coll)
|
||||
{
|
||||
return isNull(coll) || coll.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个Collection是否非空,包含List,Set,Queue
|
||||
*
|
||||
* @param coll 要判断的Collection
|
||||
* @return true:非空 false:空
|
||||
*/
|
||||
public static boolean isNotEmpty(Collection<?> coll)
|
||||
{
|
||||
return !isEmpty(coll);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个对象数组是否为空
|
||||
*
|
||||
* @param objects 要判断的对象数组
|
||||
** @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isEmpty(Object[] objects)
|
||||
{
|
||||
return isNull(objects) || (objects.length == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个对象数组是否非空
|
||||
*
|
||||
* @param objects 要判断的对象数组
|
||||
* @return true:非空 false:空
|
||||
*/
|
||||
public static boolean isNotEmpty(Object[] objects)
|
||||
{
|
||||
return !isEmpty(objects);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个Map是否为空
|
||||
*
|
||||
* @param map 要判断的Map
|
||||
* @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isEmpty(Map<?, ?> map)
|
||||
{
|
||||
return isNull(map) || map.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个Map是否为空
|
||||
*
|
||||
* @param map 要判断的Map
|
||||
* @return true:非空 false:空
|
||||
*/
|
||||
public static boolean isNotEmpty(Map<?, ?> map)
|
||||
{
|
||||
return !isEmpty(map);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个字符串是否为空串
|
||||
*
|
||||
* @param str String
|
||||
* @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isEmpty(String str)
|
||||
{
|
||||
return isNull(str) || NULLSTR.equals(str.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个字符串是否为非空串
|
||||
*
|
||||
* @param str String
|
||||
* @return true:非空串 false:空串
|
||||
*/
|
||||
public static boolean isNotEmpty(String str)
|
||||
{
|
||||
return !isEmpty(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个对象是否为空
|
||||
*
|
||||
* @param object Object
|
||||
* @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isNull(Object object)
|
||||
{
|
||||
return object == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个对象是否非空
|
||||
*
|
||||
* @param object Object
|
||||
* @return true:非空 false:空
|
||||
*/
|
||||
public static boolean isNotNull(Object object)
|
||||
{
|
||||
return !isNull(object);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个对象是否是数组类型(Java基本型别的数组)
|
||||
*
|
||||
* @param object 对象
|
||||
* @return true:是数组 false:不是数组
|
||||
*/
|
||||
public static boolean isArray(Object object)
|
||||
{
|
||||
return isNotNull(object) && object.getClass().isArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 去空格
|
||||
*/
|
||||
public static String trim(String str)
|
||||
{
|
||||
return (str == null ? "" : str.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串
|
||||
*
|
||||
* @param str 字符串
|
||||
* @param start 开始
|
||||
* @return 结果
|
||||
*/
|
||||
public static String substring(final String str, int start)
|
||||
{
|
||||
if (str == null)
|
||||
{
|
||||
return NULLSTR;
|
||||
}
|
||||
|
||||
if (start < 0)
|
||||
{
|
||||
start = str.length() + start;
|
||||
}
|
||||
|
||||
if (start < 0)
|
||||
{
|
||||
start = 0;
|
||||
}
|
||||
if (start > str.length())
|
||||
{
|
||||
return NULLSTR;
|
||||
}
|
||||
|
||||
return str.substring(start);
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串
|
||||
*
|
||||
* @param str 字符串
|
||||
* @param start 开始
|
||||
* @param end 结束
|
||||
* @return 结果
|
||||
*/
|
||||
public static String substring(final String str, int start, int end)
|
||||
{
|
||||
if (str == null)
|
||||
{
|
||||
return NULLSTR;
|
||||
}
|
||||
|
||||
if (end < 0)
|
||||
{
|
||||
end = str.length() + end;
|
||||
}
|
||||
if (start < 0)
|
||||
{
|
||||
start = str.length() + start;
|
||||
}
|
||||
|
||||
if (end > str.length())
|
||||
{
|
||||
end = str.length();
|
||||
}
|
||||
|
||||
if (start > end)
|
||||
{
|
||||
return NULLSTR;
|
||||
}
|
||||
|
||||
if (start < 0)
|
||||
{
|
||||
start = 0;
|
||||
}
|
||||
if (end < 0)
|
||||
{
|
||||
end = 0;
|
||||
}
|
||||
|
||||
return str.substring(start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化文本, {} 表示占位符<br>
|
||||
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
|
||||
* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
|
||||
* 例:<br>
|
||||
* 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
|
||||
* 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
|
||||
* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
|
||||
*
|
||||
* @param template 文本模板,被替换的部分用 {} 表示
|
||||
* @param params 参数值
|
||||
* @return 格式化后的文本
|
||||
*/
|
||||
// public static String format(String template, Object... params)
|
||||
// {
|
||||
// if (isEmpty(params) || isEmpty(template))
|
||||
// {
|
||||
// return template;
|
||||
// }
|
||||
// return StrFormatter.format(template, params);
|
||||
// }
|
||||
|
||||
/**
|
||||
* 下划线转驼峰命名
|
||||
*/
|
||||
public static String toUnderScoreCase(String str)
|
||||
{
|
||||
if (str == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
// 前置字符是否大写
|
||||
boolean preCharIsUpperCase = true;
|
||||
// 当前字符是否大写
|
||||
boolean curreCharIsUpperCase = true;
|
||||
// 下一字符是否大写
|
||||
boolean nexteCharIsUpperCase = true;
|
||||
for (int i = 0; i < str.length(); i++)
|
||||
{
|
||||
char c = str.charAt(i);
|
||||
if (i > 0)
|
||||
{
|
||||
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
preCharIsUpperCase = false;
|
||||
}
|
||||
|
||||
curreCharIsUpperCase = Character.isUpperCase(c);
|
||||
|
||||
if (i < (str.length() - 1))
|
||||
{
|
||||
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
|
||||
}
|
||||
|
||||
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase)
|
||||
{
|
||||
sb.append(SEPARATOR);
|
||||
}
|
||||
else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase)
|
||||
{
|
||||
sb.append(SEPARATOR);
|
||||
}
|
||||
sb.append(Character.toLowerCase(c));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否包含字符串
|
||||
*
|
||||
* @param str 验证字符串
|
||||
* @param strs 字符串组
|
||||
* @return 包含返回true
|
||||
*/
|
||||
public static boolean inStringIgnoreCase(String str, String... strs)
|
||||
{
|
||||
if (str != null && strs != null)
|
||||
{
|
||||
for (String s : strs)
|
||||
{
|
||||
if (str.equalsIgnoreCase(trim(s)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld
|
||||
*
|
||||
* @param name 转换前的下划线大写方式命名的字符串
|
||||
* @return 转换后的驼峰式命名的字符串
|
||||
*/
|
||||
public static String convertToCamelCase(String name)
|
||||
{
|
||||
StringBuilder result = new StringBuilder();
|
||||
// 快速检查
|
||||
if (name == null || name.isEmpty())
|
||||
{
|
||||
// 没必要转换
|
||||
return "";
|
||||
}
|
||||
else if (!name.contains("_"))
|
||||
{
|
||||
// 不含下划线,仅将首字母大写
|
||||
return name.substring(0, 1).toUpperCase() + name.substring(1);
|
||||
}
|
||||
// 用下划线将原始字符串分割
|
||||
String[] camels = name.split("_");
|
||||
for (String camel : camels)
|
||||
{
|
||||
// 跳过原始字符串中开头、结尾的下换线或双重下划线
|
||||
if (camel.isEmpty())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 首字母大写
|
||||
result.append(camel.substring(0, 1).toUpperCase());
|
||||
result.append(camel.substring(1).toLowerCase());
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 驼峰式命名法 例如:user_name->userName
|
||||
*/
|
||||
public static String toCamelCase(String s)
|
||||
{
|
||||
if (s == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
s = s.toLowerCase();
|
||||
StringBuilder sb = new StringBuilder(s.length());
|
||||
boolean upperCase = false;
|
||||
for (int i = 0; i < s.length(); i++)
|
||||
{
|
||||
char c = s.charAt(i);
|
||||
|
||||
if (c == SEPARATOR)
|
||||
{
|
||||
upperCase = true;
|
||||
}
|
||||
else if (upperCase)
|
||||
{
|
||||
sb.append(Character.toUpperCase(c));
|
||||
upperCase = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T cast(Object obj)
|
||||
{
|
||||
return (T) obj;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 判断对象或对象数组中每一个对象是否为空: 对象为null,字符序列长度为0,集合类、Map为empty
|
||||
*
|
||||
* @param obj
|
||||
* @return
|
||||
*/
|
||||
public static boolean isNullOrEmpty(Object obj) {
|
||||
|
||||
if (obj == null) return true;
|
||||
|
||||
if (obj instanceof CharSequence) return ((CharSequence) obj).length() == 0;
|
||||
|
||||
if (obj instanceof Collection) return ((Collection) obj).isEmpty();
|
||||
|
||||
if (obj instanceof Map) return ((Map) obj).isEmpty();
|
||||
|
||||
if (obj instanceof Object[]) {
|
||||
Object[] object = (Object[]) obj;
|
||||
if (object.length == 0) {
|
||||
return true;
|
||||
}
|
||||
boolean empty = true;
|
||||
for (int i = 0; i < object.length; i++) {
|
||||
if (!isNullOrEmpty(object[i])) {
|
||||
empty = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return empty;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.coobird.thumbnailator.Thumbnails;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
@Slf4j
|
||||
public class ThumbnailsUtils{
|
||||
|
||||
/**
|
||||
* 通过BufferedImage图片流调整图片大小
|
||||
*/
|
||||
public static BufferedImage resizeImageOne(BufferedImage originalImage, int targetWidth, int targetHeight) throws Exception {
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
Thumbnails.of(originalImage)
|
||||
.size(targetWidth, targetHeight)
|
||||
.outputFormat("JPEG")
|
||||
.outputQuality(1)
|
||||
.toOutputStream(outputStream);
|
||||
byte[] data = outputStream.toByteArray();
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
|
||||
return ImageIO.read(inputStream);
|
||||
}
|
||||
|
||||
/**
|
||||
* BufferedImage图片流转byte[]数组
|
||||
*/
|
||||
public static byte[] imageToBytes(BufferedImage bImage) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try {
|
||||
ImageIO.write(bImage, "jpg", out);
|
||||
} catch (IOException e) {
|
||||
log.error("错误信息: ", e);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* byte[]数组转BufferedImage图片流
|
||||
*/
|
||||
private static BufferedImage bytesToBufferedImage(byte[] ImageByte) {
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(ImageByte);
|
||||
BufferedImage image = null;
|
||||
try {
|
||||
image = ImageIO.read(in);
|
||||
} catch (IOException e) {
|
||||
log.error("错误信息: ", e);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,448 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import net.shapelight.modules.sys.entity.SysDeptEntity;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.*;
|
||||
|
||||
public class TreeUtils {
|
||||
|
||||
/*public static boolean isEmpty(String str) {
|
||||
if (str != null && !"".equals(str.trim())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}*/
|
||||
|
||||
/**
|
||||
* 集合转树结构
|
||||
*
|
||||
* @param collection 目标集合
|
||||
* @param clazz 集合元素类型
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
public static <T> Collection<T> toTree(@NotNull Collection<T> collection, @NotNull Class<T> clazz) {
|
||||
return toTree(collection, null, null, null, clazz);
|
||||
}
|
||||
|
||||
/**
|
||||
* 集合转树结构,注意,使用此方法,则集合元素必须继承ITree接口
|
||||
*
|
||||
* @param collection 目标集合
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
public static <T extends ITree> Collection<T> toTree(@NotNull Collection<T> collection) {
|
||||
try {
|
||||
if (collection == null || collection.isEmpty()) return null;// 如果目标集合为空,直接返回一个空树
|
||||
// 找出所有的根节点
|
||||
Collection<T> roots = null;
|
||||
if (collection.getClass().isAssignableFrom(Set.class)) roots = new HashSet<>();
|
||||
else roots = new ArrayList<>();
|
||||
for (T tree : collection) {
|
||||
Object o = ITree.class.getMethod("getParent").invoke(tree);
|
||||
if (o instanceof String) {
|
||||
if (StringUtils.isEmpty((String) o)) {
|
||||
roots.add(tree);
|
||||
}
|
||||
} else if (o == null) {
|
||||
roots.add(tree);
|
||||
}
|
||||
}
|
||||
// 从目标集合移除所有的根节点
|
||||
collection.removeAll(roots);
|
||||
// 为根节点添加孩子节点
|
||||
for (T tree : roots) {
|
||||
addChild(tree, collection);
|
||||
}
|
||||
return roots;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 集合转树结构
|
||||
*
|
||||
* @param collection 目标集合
|
||||
* @param id 被依赖字段名称
|
||||
* @param parent 依赖字段名称
|
||||
* @param children 子节点集合属性名称
|
||||
* @param clazz 集合元素类型
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
public static <T> Collection<T> toTree(@NotNull Collection<T> collection, String id, String parent, String children, @NotNull Class<T> clazz) {
|
||||
try {
|
||||
if (collection == null || collection.isEmpty()) return null;// 如果目标集合为空,直接返回一个空树
|
||||
if (StringUtils.isEmpty(id)) id = "id";// 如果被依赖字段名称为空则默认为id
|
||||
if (StringUtils.isEmpty(parent)) parent = "parent";// 如果依赖字段为空则默认为parent
|
||||
if (StringUtils.isEmpty(children)) children = "children";// 如果子节点集合属性名称为空则默认为children
|
||||
Collection<T> roots = null;// 初始化根节点集合
|
||||
if (collection.getClass().isAssignableFrom(Set.class))
|
||||
roots = new HashSet<>();// 如果目标节点是一个set集合,则初始化根节点集合为hashset
|
||||
else roots = new ArrayList<>();// 否则初始化为Arraylist,
|
||||
// 这里集合初始化只分2中,要么是hashset,要么ArrayList,因为这两种最常用,其他不常用的摒弃
|
||||
Field idField = null;
|
||||
try {
|
||||
idField = clazz.getDeclaredField(id);// 获取依赖字段
|
||||
} catch (NoSuchFieldException e1) {
|
||||
idField = clazz.getSuperclass().getDeclaredField(id);
|
||||
}
|
||||
Field parentField = null;
|
||||
try {
|
||||
parentField = clazz.getDeclaredField(parent);// 获取被依赖字段
|
||||
} catch (NoSuchFieldException e1) {
|
||||
parentField = clazz.getSuperclass().getDeclaredField(parent);
|
||||
}
|
||||
Field childrenField = null;// 获取孩子字段
|
||||
try {
|
||||
childrenField = clazz.getDeclaredField(children);
|
||||
} catch (NoSuchFieldException e1) {
|
||||
childrenField = clazz.getSuperclass().getDeclaredField(children);
|
||||
}
|
||||
// 设置为可访问
|
||||
idField.setAccessible(true);
|
||||
parentField.setAccessible(true);
|
||||
childrenField.setAccessible(true);
|
||||
// 找出所有的根节点
|
||||
/*for (T c : collection) {
|
||||
Object o = parentField.get(c);
|
||||
if (o instanceof String) {
|
||||
if (StringUtils.isEmpty((String) o)) {// 如果父节点为空则说明是根节点,添加到根节点集合
|
||||
roots.add(c);
|
||||
}
|
||||
} else {
|
||||
if (o == null) {
|
||||
roots.add(c);
|
||||
}
|
||||
}
|
||||
}*/
|
||||
for (T c : collection) {
|
||||
Object o = parentField.get(c);
|
||||
if (o instanceof Long) {
|
||||
if (((Long)o).longValue() == 0L) {// 如果父节点为空则说明是根节点,添加到根节点集合
|
||||
roots.add(c);
|
||||
}
|
||||
} else {
|
||||
if (o == null) {
|
||||
roots.add(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 从目标集合移除所有根节点
|
||||
collection.removeAll(roots);
|
||||
for (T c : roots) {// 遍历根节点,依次添加子节点
|
||||
addChild(c, collection, idField, parentField, childrenField);
|
||||
}
|
||||
// 关闭可访问
|
||||
idField.setAccessible(false);
|
||||
parentField.setAccessible(false);
|
||||
childrenField.setAccessible(false);
|
||||
return roots;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T extends ITree> void addChild(T tree, Collection<T> collection) {
|
||||
try {
|
||||
Object id = ITree.class.getMethod("getId").invoke(tree);
|
||||
Collection<T> children = (Collection<T>) ITree.class.getMethod("getChildren").invoke(tree);
|
||||
for (T cc : collection) {
|
||||
Object o = ITree.class.getMethod("getParent").invoke(cc);
|
||||
if (id.equals(o)) {// 如果当前节点的被依赖值和目标节点的被依赖值相等,则说明,当前节点是目标节点的子节点
|
||||
if (children == null) {// 如果目标节点的孩子集合为null,初始化目标节点的孩子集合
|
||||
if (collection.getClass().isAssignableFrom(Set.class)) {// 如果目标集合是一个set集合,则初始化目标节点的孩子节点集合为set
|
||||
children = new HashSet<>();
|
||||
} else children = new ArrayList<>();// 否则初始化为list
|
||||
}
|
||||
// 将当前节点添加到目标节点的孩子节点
|
||||
children.add(cc);
|
||||
// 重设目标节点的孩子节点集合,这里必须重设,因为如果目标节点的孩子节点是null的话,这样是没有地址的,就会造成数据丢失,所以必须重设,如果目标节点所在类的孩子节点初始化为一个空集合,而不是null,则可以不需要这一步,因为java一切皆指针
|
||||
ITree.class.getMethod("setChildren", Collection.class).invoke(tree, children);
|
||||
// 递归添加孩子节点
|
||||
addChild(cc, collection);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 为目标节点添加孩子节点,此方法为私有,不能为公开,否则类修改信息无法恢复,后面有公开方法,其专门为目标节点添加子节点
|
||||
*
|
||||
* @param c 目标节点
|
||||
* @param collection 目标集合
|
||||
* @param idField
|
||||
* @param parentField
|
||||
* @param childrenField
|
||||
* @param <T>
|
||||
* @throws IllegalAccessException
|
||||
*/
|
||||
private static <T> void addChild(@NotNull T c, @NotNull Collection<T> collection, @NotNull Field idField, @NotNull Field parentField, @NotNull Field childrenField) throws IllegalAccessException {
|
||||
Object id = idField.get(c);// 获取目标节点的被依赖值
|
||||
Collection<T> children = (Collection<T>) childrenField.get(c);// 获取目标节点的孩子列表
|
||||
for (T cc : collection) {// 遍历目标集合
|
||||
Object o = parentField.get(cc);// 获取当前节点的依赖值
|
||||
if (id.equals(o)) {// 如果当前节点的被依赖值和目标节点的被依赖值相等,则说明,当前节点是目标节点的子节点
|
||||
if (children == null) {// 如果目标节点的孩子集合为null,初始化目标节点的孩子集合
|
||||
if (collection.getClass().isAssignableFrom(Set.class)) {// 如果目标集合是一个set集合,则初始化目标节点的孩子节点集合为set
|
||||
children = new HashSet<>();
|
||||
} else children = new ArrayList<>();// 否则初始化为list
|
||||
}
|
||||
// 将当前节点添加到目标节点的孩子节点
|
||||
children.add(cc);
|
||||
// 重设目标节点的孩子节点集合,这里必须重设,因为如果目标节点的孩子节点是null的话,这样是没有地址的,就会造成数据丢失,所以必须重设,如果目标节点所在类的孩子节点初始化为一个空集合,而不是null,则可以不需要这一步,因为java一切皆指针
|
||||
childrenField.set(c, children);
|
||||
// 递归添加孩子节点
|
||||
addChild(cc, collection, idField, parentField, childrenField);
|
||||
}
|
||||
}
|
||||
// 特别说明:大家可以看到此递归没有明显出口,其出口就是是否当前节点的依赖值和目标节点的被依赖值一样,一样就递归,不一样进不了if,自然出递归
|
||||
// 此工具类自我感觉是最简单的,最实用的工具类,我看网上许多人写的,都是云的雾的,本来也想借鉴,但是实在没一个能看的感觉思路清晰,没办法,自己动手造轮子
|
||||
}
|
||||
|
||||
/**
|
||||
* 为目标节点添加孩子
|
||||
*
|
||||
* @param c 目标节点
|
||||
* @param collection 目标集合
|
||||
* @param id 被依赖字段名
|
||||
* @param parent 依赖字段名
|
||||
* @param children 孩子节点字段名
|
||||
* @param clazz 集合元素所在类别
|
||||
* @param <T>
|
||||
*/
|
||||
public static <T> void addChild(@NotNull T c, @NotNull Collection<T> collection, String id, String parent, String children, @NotNull Class<T> clazz) {
|
||||
try {
|
||||
if (collection == null || collection.isEmpty()) return;// 如果目标集合为空,直接返回一个空树
|
||||
if (StringUtils.isEmpty(id)) id = "id";// 如果被依赖字段名称为空则默认为id
|
||||
if (StringUtils.isEmpty(parent)) parent = "parent";// 如果依赖字段为空则默认为parent
|
||||
if (StringUtils.isEmpty(children)) children = "children";// 如果子节点集合属性名称为空则默认为children
|
||||
Field idField = null;
|
||||
try {
|
||||
idField = clazz.getDeclaredField(id);// 获取依赖字段
|
||||
} catch (NoSuchFieldException e1) {
|
||||
idField = clazz.getSuperclass().getDeclaredField(id);
|
||||
}
|
||||
Field parentField = null;
|
||||
try {
|
||||
parentField = clazz.getDeclaredField(parent);// 获取被依赖字段
|
||||
} catch (NoSuchFieldException e1) {
|
||||
parentField = clazz.getSuperclass().getDeclaredField(parent);
|
||||
}
|
||||
Field childrenField = null;// 获取孩子字段
|
||||
try {
|
||||
childrenField = clazz.getDeclaredField(children);
|
||||
} catch (NoSuchFieldException e1) {
|
||||
childrenField = clazz.getSuperclass().getDeclaredField(children);
|
||||
}
|
||||
// 设置为可访问
|
||||
idField.setAccessible(true);
|
||||
parentField.setAccessible(true);
|
||||
childrenField.setAccessible(true);
|
||||
addChild(c, collection, idField, parentField, childrenField);
|
||||
// 关闭可访问
|
||||
idField.setAccessible(false);
|
||||
parentField.setAccessible(false);
|
||||
childrenField.setAccessible(false);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 为目标节点添加孩子
|
||||
*
|
||||
* @param c 目标节点
|
||||
* @param collection 目标集合
|
||||
* @param clazz 集合元素所在类型
|
||||
* @param <T>
|
||||
*/
|
||||
public static <T> void addChild(@NotNull T c, @NotNull Collection<T> collection, @NotNull Class<T> clazz) {
|
||||
addChild(c, collection, null, null, null, clazz);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
- listToTree
|
||||
- <p>方法说明<p>
|
||||
- 将JSONArray数组转为树状结构
|
||||
- @param arr 需要转化的数据
|
||||
- @param id 数据唯一的标识键值
|
||||
- @param pid 父id唯一标识键值
|
||||
- @param child 子节点键值
|
||||
- @return JSONArray
|
||||
*/
|
||||
public static JSONArray listToTree(JSONArray arr, String id, String pid, String child){
|
||||
JSONArray r = new JSONArray();
|
||||
JSONObject hash = new JSONObject();
|
||||
//将数组转为Object的形式,key为数组中的id
|
||||
for(int i=0;i<arr.size();i++){
|
||||
JSONObject json = (JSONObject) arr.get(i);
|
||||
hash.put(json.getString(id), json);
|
||||
}
|
||||
//遍历结果集
|
||||
for(int j=0;j<arr.size();j++){
|
||||
//单条记录
|
||||
JSONObject aVal = (JSONObject) arr.get(j);
|
||||
//在hash中取出key为单条记录中pid的值
|
||||
JSONObject hashVP = (JSONObject) hash.get(aVal.get(pid).toString());
|
||||
//如果记录的pid存在,则说明它有父节点,将她添加到孩子节点的集合中
|
||||
if(hashVP!=null){
|
||||
//检查是否有child属性
|
||||
if(hashVP.get(child)!=null){
|
||||
JSONArray ch = (JSONArray) hashVP.get(child);
|
||||
ch.add(aVal);
|
||||
hashVP.put(child, ch);
|
||||
}else{
|
||||
JSONArray ch = new JSONArray();
|
||||
ch.add(aVal);
|
||||
hashVP.put(child, ch);
|
||||
}
|
||||
}else{
|
||||
r.add(aVal);
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 树形数据转换
|
||||
* @param {*} data
|
||||
* @param {*} id
|
||||
* @param {*} pid
|
||||
*/
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<Menu> list = new ArrayList<>();
|
||||
list.add(new Menu(1, 100));
|
||||
list.add(new Menu(2, 100));
|
||||
list.add(new Menu(3, 100));
|
||||
list.add(new Menu(4, 1));
|
||||
list.add(new Menu(5, 1));
|
||||
list.add(new Menu(6, 1));
|
||||
list.add(new Menu(7, 2));
|
||||
list.add(new Menu(8, 2));
|
||||
list.add(new Menu(9, 3));
|
||||
list.add(new Menu(10, 4));
|
||||
list.add(new Menu(11, 7));
|
||||
list.add(new Menu(12, 5));
|
||||
list.add(new Menu(13, 10));
|
||||
list.add(new Menu(14, 8));
|
||||
list.add(new Menu(15, 11));
|
||||
list.add(new Menu(16, 12));
|
||||
list.add(new Menu(17, 13));
|
||||
|
||||
List<SysDeptEntity> deptList = new ArrayList<>();
|
||||
SysDeptEntity s = new SysDeptEntity();
|
||||
s.setDeptId(2L);
|
||||
s.setParentId(7L);
|
||||
s.setName("系统管理");
|
||||
deptList.add(s);
|
||||
|
||||
s = new SysDeptEntity();
|
||||
s.setDeptId(6L);
|
||||
s.setParentId(2L);
|
||||
deptList.add(s);
|
||||
|
||||
s = new SysDeptEntity();
|
||||
s.setDeptId(8L);
|
||||
s.setParentId(6L);
|
||||
deptList.add(s);
|
||||
|
||||
s = new SysDeptEntity();
|
||||
s.setDeptId(9L);
|
||||
s.setParentId(8L);
|
||||
deptList.add(s);
|
||||
|
||||
//Collection<Menu> menus = TreeUtils.toTree(list, null, null, null, Menu.class);
|
||||
//System.out.println(JSON.toJSONString(menus));
|
||||
|
||||
|
||||
//Collection<SysDeptEntity> depts = TreeUtils.toTree(deptList, "deptId", "parentId", "childrenList", SysDeptEntity.class);
|
||||
//System.out.println(JSON.toJSONString(depts));
|
||||
|
||||
|
||||
|
||||
/*List<SysDeptEntity> deptList = new ArrayList<>();
|
||||
SysDeptEntity s = new SysDeptEntity();
|
||||
s.setDeptId(2L);
|
||||
s.setParentId(7L);
|
||||
s.setName("系统管理");
|
||||
deptList.add(s);
|
||||
|
||||
s = new SysDeptEntity();
|
||||
s.setDeptId(6L);
|
||||
s.setParentId(2L);
|
||||
s.setName("用户管理");
|
||||
deptList.add(s);*/
|
||||
|
||||
|
||||
System.out.println(JSON.toJSONString(deptList));
|
||||
JSONArray deptTree = listToTree(JSONArray.parseArray(JSON.toJSONString(deptList)),"deptId","parentId","childrenList");
|
||||
System.out.println(JSON.toJSONString(deptTree));
|
||||
|
||||
System.out.println(JSON.toJSONString(list));
|
||||
JSONArray listTree = listToTree(JSONArray.parseArray(JSON.toJSONString(list)),"id","parent","children");
|
||||
System.out.println(JSON.toJSONString(listTree));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
class Menu {
|
||||
private Integer id;
|
||||
private Integer parent;
|
||||
private List<Menu> children;
|
||||
|
||||
public Menu() {
|
||||
}
|
||||
|
||||
public Menu(Integer id, Integer parent) {
|
||||
this.id = id;
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
public List<Menu> getChildren() {
|
||||
return children;
|
||||
}
|
||||
|
||||
public void setChildren(List<Menu> children) {
|
||||
this.children = children;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
public void setParent(Integer parent) {
|
||||
this.parent = parent;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class UUIDUtil {
|
||||
public static String uuid(){
|
||||
return UUID.randomUUID().toString().replace("-","");
|
||||
}
|
||||
public static void main(String args[]){
|
||||
String uuid = UUIDUtil.uuid();
|
||||
System.out.println(uuid);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,181 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.File;
|
||||
import java.util.Date;
|
||||
|
||||
|
||||
/**
|
||||
* 上传文件工具类
|
||||
*
|
||||
*/
|
||||
public class UploadZipUtil {
|
||||
|
||||
/**
|
||||
* 解析上传的压缩文件
|
||||
* @param request 请求
|
||||
* @param file 上传文件
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String resolveCompressUploadFile(HttpServletRequest request, MultipartFile file, String path) throws Exception {
|
||||
|
||||
/* 截取后缀名 */
|
||||
if (file.isEmpty()) {
|
||||
throw new Exception("文件不能为空");
|
||||
}
|
||||
String fileName = file.getOriginalFilename();
|
||||
int pos = fileName.lastIndexOf(".");
|
||||
String extName = fileName.substring(pos+1).toLowerCase();
|
||||
//判断上传文件必须是zip或者是rar否则不允许上传
|
||||
//if (!extName.equals("zip")&&!extName.equals("rar")) {
|
||||
if (!extName.equals("zip")) {
|
||||
throw new Exception("上传文件格式错误,仅支持zip压缩文件");
|
||||
}
|
||||
// UUID后缀名保存
|
||||
//时间保存
|
||||
String saveName = UUIDUtil.uuid()+ "."+extName;
|
||||
//String saveName = DateUtil.date2String(new Date(),"yyyyMMddHHmmss")+ "."+extName;
|
||||
//文件名
|
||||
String saveFileName = saveName.substring(0, saveName.lastIndexOf("."));
|
||||
// 根据服务器的文件保存地址和原文件名创建目录文件全路径
|
||||
File pushFile = new File(path + "/" +saveFileName+"/"+ saveName);
|
||||
|
||||
File descFile = new File(path+"/"+saveFileName);
|
||||
if (!descFile.exists()) {
|
||||
descFile.mkdirs();
|
||||
}
|
||||
//解压目的文件
|
||||
//String descDir = path +"/"+saveFileName+"/";
|
||||
String descDir = path +"/";
|
||||
String unZipDir = path +"/"+saveFileName+"/";
|
||||
|
||||
file.transferTo(pushFile);
|
||||
|
||||
//开始解压zip
|
||||
if (extName.equals("zip")) {
|
||||
//CompressZipUtils.unZipFiles(pushFile, descDir);
|
||||
CompressZipUtils.unZipFiles(pushFile, unZipDir);
|
||||
|
||||
}
|
||||
// else if (extName.equals("rar")) {
|
||||
// //开始解压rar
|
||||
// //CompressZipUtils.unRarFile(pushFile.getAbsolutePath(), descDir);
|
||||
//
|
||||
// }
|
||||
else {
|
||||
throw new Exception("文件格式不正确不能解压");
|
||||
}
|
||||
//遍历文件夹
|
||||
// boolean isExist = checkIndexHtml(descDir);
|
||||
// if(!isExist){
|
||||
// throw new Exception("文件中缺少index.html");
|
||||
// }
|
||||
return saveFileName;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static String unZipGifFromSourceFile(MultipartFile file, String path) throws Exception {
|
||||
|
||||
/* 截取后缀名 */
|
||||
if (file.isEmpty()) {
|
||||
throw new Exception("文件不能为空");
|
||||
}
|
||||
String fileName = file.getOriginalFilename();
|
||||
int pos = fileName.lastIndexOf(".");
|
||||
String extName = fileName.substring(pos+1).toLowerCase();
|
||||
//判断上传文件必须是zip或者是rar否则不允许上传
|
||||
//if (!extName.equals("zip")&&!extName.equals("rar")) {
|
||||
if (!extName.equals("zip")) {
|
||||
throw new Exception("上传文件格式错误,仅支持zip压缩文件");
|
||||
}
|
||||
// UUID后缀名保存
|
||||
//时间保存
|
||||
String saveName = UUIDUtil.uuid()+ "."+extName;
|
||||
//String saveName = DateUtil.date2String(new Date(),"yyyyMMddHHmmss")+ "."+extName;
|
||||
//文件名
|
||||
String saveFileName = saveName.substring(0, saveName.lastIndexOf("."));
|
||||
// 根据服务器的文件保存地址和原文件名创建目录文件全路径
|
||||
File pushFile = new File(path + "/" +saveFileName+"/"+ saveName);
|
||||
|
||||
File descFile = new File(path+"/"+saveFileName);
|
||||
if (!descFile.exists()) {
|
||||
descFile.mkdirs();
|
||||
}
|
||||
//解压目的文件
|
||||
//String descDir = path +"/"+saveFileName+"/";
|
||||
String descDir = path +"/";
|
||||
String unZipDir = path +"/"+saveFileName+"/";
|
||||
|
||||
file.transferTo(pushFile);
|
||||
|
||||
//开始解压zip
|
||||
if (extName.equals("zip")) {
|
||||
//CompressZipUtils.unZipFiles(pushFile, descDir);
|
||||
CompressZipUtils.unZipFiles(pushFile, unZipDir);
|
||||
|
||||
}
|
||||
else {
|
||||
throw new Exception("文件格式不正确不能解压");
|
||||
}
|
||||
String resFileName = "";
|
||||
//遍历文件夹
|
||||
for (File fileGif : new File(unZipDir).listFiles()) {
|
||||
String gifname = fileGif.getName();
|
||||
if(gifname.equals("head.gif")){
|
||||
resFileName = fileGif.getAbsolutePath();
|
||||
System.out.println("GIF:"+resFileName);
|
||||
}else{
|
||||
fileGif.delete();
|
||||
}
|
||||
}
|
||||
return resFileName;
|
||||
}
|
||||
|
||||
|
||||
// public static void unzip(String zipFilePath, String destDir) {
|
||||
// File dir = new File(destDir);
|
||||
//
|
||||
// // 创建输出目录如果它不存在
|
||||
// if (!dir.exists()) dir.mkdirs();
|
||||
//
|
||||
// byte[] buffer = new byte[1024];
|
||||
// try {
|
||||
// FileInputStream fis = new FileInputStream(zipFilePath);
|
||||
// ZipInputStream zis = new ZipInputStream(fis);
|
||||
// ZipEntry ze = zis.getNextEntry();
|
||||
//
|
||||
// while (ze != null) {
|
||||
// String fileName = ze.getName();
|
||||
// File newFile = new File(destDir + File.separator + fileName);
|
||||
//
|
||||
// // 创建所有非存在的父目录
|
||||
// new File(newFile.getParent()).mkdirs();
|
||||
//
|
||||
// FileOutputStream fos = new FileOutputStream(newFile);
|
||||
//
|
||||
// int len;
|
||||
// while ((len = zis.read(buffer)) > 0) {
|
||||
// fos.write(buffer, 0, len);
|
||||
// }
|
||||
//
|
||||
// fos.close();
|
||||
// // 关闭当前ZipEntry并移至下一个
|
||||
// zis.closeEntry();
|
||||
// ze = zis.getNextEntry();
|
||||
// }
|
||||
//
|
||||
// // 关闭最后一个ZipEntry
|
||||
// zis.closeEntry();
|
||||
// zis.close();
|
||||
// fis.close();
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,107 @@
|
|||
package net.shapelight.common.utils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public class ZipExample {
|
||||
// public static void main(String[] args) {
|
||||
// String zipFileName = "/home/huangyifang/gb/palm/temp/20323/example.zip";
|
||||
// String folderToCompress = "/home/huangyifang/gb/palm/temp/20323";
|
||||
//
|
||||
// try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName))) {
|
||||
// // 压缩文件夹
|
||||
// compressFolder(folderToCompress, folderToCompress, zipOutputStream);
|
||||
//
|
||||
// System.out.println("Folder compressed successfully!");
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private static void compressFolder(String sourceFolder, String folderName, ZipOutputStream zipOutputStream) throws IOException {
|
||||
// File folder = new File(sourceFolder);
|
||||
// File[] files = folder.listFiles();
|
||||
//
|
||||
// if (files != null) {
|
||||
// for (File file : files) {
|
||||
// if (file.isDirectory()) {
|
||||
// // 压缩子文件夹
|
||||
// compressFolder(file.getAbsolutePath(), folderName + "/" + file.getName(), zipOutputStream);
|
||||
// } else {
|
||||
// // 压缩文件
|
||||
// addToZipFile(folderName + "/" + file.getName(), file.getAbsolutePath(), zipOutputStream);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private static void addToZipFile(String fileName, String fileAbsolutePath, ZipOutputStream zipOutputStream) throws IOException {
|
||||
// // 创建ZipEntry对象并设置文件名
|
||||
// ZipEntry entry = new ZipEntry(fileName);
|
||||
// zipOutputStream.putNextEntry(entry);
|
||||
//
|
||||
// // 读取文件内容并写入Zip文件
|
||||
// try (FileInputStream fileInputStream = new FileInputStream(fileAbsolutePath)) {
|
||||
// byte[] buffer = new byte[1024];
|
||||
// int bytesRead;
|
||||
// while ((bytesRead = fileInputStream.read(buffer)) != -1) {
|
||||
// zipOutputStream.write(buffer, 0, bytesRead);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 完成当前文件的压缩
|
||||
// zipOutputStream.closeEntry();
|
||||
// }
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 要压缩的文件或文件夹
|
||||
String sourceFile = "/home/huangyifang/project/cell/temp/b68fa15aa7c146f6aa453475981f0b7e";
|
||||
|
||||
// 压缩后的ZIP文件名
|
||||
String zipFileName = "/home/huangyifang/project/cell/temp/b68fa15aa7c146f6aa453475981f0b7e.zip";
|
||||
|
||||
// 创建一个输出流将数据写入ZIP文件
|
||||
try (FileOutputStream fos = new FileOutputStream(zipFileName);
|
||||
ZipOutputStream zos = new ZipOutputStream(fos)) {
|
||||
|
||||
// 调用递归方法压缩文件或文件夹
|
||||
addToZipFile(sourceFile, sourceFile, zos);
|
||||
|
||||
System.out.println("文件已成功打包成 " + zipFileName);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void addToZipFile(String path, String sourceFile, ZipOutputStream zos) throws IOException {
|
||||
File file = new File(sourceFile);
|
||||
|
||||
// 如果是文件夹,则获取其内容并递归调用此方法
|
||||
if (file.isDirectory()) {
|
||||
String[] fileList = file.list();
|
||||
if (fileList != null) {
|
||||
for (String fileName : fileList) {
|
||||
addToZipFile(path, sourceFile + File.separator + fileName, zos);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果是文件,则将其添加到ZIP文件中
|
||||
try (FileInputStream fis = new FileInputStream(sourceFile)) {
|
||||
String entryName = sourceFile.substring(path.length() + 1); // 获取ZIP中的条目名称
|
||||
ZipEntry zipEntry = new ZipEntry(entryName);
|
||||
zos.putNextEntry(zipEntry);
|
||||
|
||||
byte[] bytes = new byte[1024];
|
||||
int length;
|
||||
while ((length = fis.read(bytes)) >= 0) {
|
||||
zos.write(bytes, 0, length);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package net.shapelight.common.validator.group;
|
||||
|
||||
/**
|
||||
* 新增数据 Group
|
||||
*
|
||||
*/
|
||||
public interface AddGroup {
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
|
||||
|
||||
package net.shapelight.common.validator.group;
|
||||
|
||||
/**
|
||||
* 阿里云
|
||||
*
|
||||
*
|
||||
*/
|
||||
public interface AliyunGroup {
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package net.shapelight.common.validator.group;
|
||||
|
||||
import javax.validation.GroupSequence;
|
||||
|
||||
/**
|
||||
* 定义校验顺序,如果AddGroup组失败,则UpdateGroup组不会再校验
|
||||
*
|
||||
*/
|
||||
@GroupSequence({AddGroup.class, UpdateGroup.class})
|
||||
public interface Group {
|
||||
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
|
||||
|
||||
package net.shapelight.common.validator.group;
|
||||
|
||||
/**
|
||||
* 腾讯云
|
||||
*
|
||||
*
|
||||
*/
|
||||
public interface QcloudGroup {
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
|
||||
|
||||
package net.shapelight.common.validator.group;
|
||||
|
||||
/**
|
||||
* 七牛
|
||||
*
|
||||
*
|
||||
*/
|
||||
public interface QiniuGroup {
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
|
||||
|
||||
package net.shapelight.common.validator.group;
|
||||
|
||||
/**
|
||||
* 更新数据 Group
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
public interface UpdateGroup {
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package net.shapelight.modules.app.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* app登录效验
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface Login {
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package net.shapelight.modules.app.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 登录用户信息
|
||||
*/
|
||||
@Target(ElementType.PARAMETER)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface LoginUser {
|
||||
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package net.shapelight.modules.app.config;
|
||||
|
||||
import net.shapelight.modules.app.interceptor.AuthorizationInterceptor;
|
||||
import net.shapelight.modules.app.resolver.LoginUserHandlerMethodArgumentResolver;
|
||||
import net.shapelight.modules.appparent.interceptor.ParentAuthorizationInterceptor;
|
||||
import net.shapelight.modules.appparent.resolver.ParentLoginUserHandlerMethodArgumentResolver;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* MVC配置
|
||||
*/
|
||||
@Configuration
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
@Autowired
|
||||
private AuthorizationInterceptor authorizationInterceptor;
|
||||
@Autowired
|
||||
private ParentAuthorizationInterceptor parentAuthorizationInterceptor;
|
||||
@Autowired
|
||||
private LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver;
|
||||
@Autowired
|
||||
private ParentLoginUserHandlerMethodArgumentResolver parentLoginUserHandlerMethodArgumentResolver;
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(authorizationInterceptor).addPathPatterns("/app/**");
|
||||
registry.addInterceptor(parentAuthorizationInterceptor).addPathPatterns("/parent/app/**");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
|
||||
argumentResolvers.add(loginUserHandlerMethodArgumentResolver);
|
||||
argumentResolvers.add(parentLoginUserHandlerMethodArgumentResolver);
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,16 @@
|
|||
package net.shapelight.modules.app.controller;
|
||||
|
||||
public class AppComm {
|
||||
public static int FLAG_DEVICE_ALART = 2;
|
||||
public static int FLAG_APP_TO_SERVER = 0;
|
||||
public static int FLAG_SERVER_TO_DEVICE = 1;
|
||||
public static int FLAG_RESPONSED = 3;
|
||||
public static int FLAG_ALERT_MSG_DELETE = 4;
|
||||
public static String STRING_ALEAM = "告警";
|
||||
public static String TYPE_MOVECAR = "movecar";
|
||||
public static String SIGNAL_STATUS_ON = "正常";
|
||||
public static String SIGNAL_STATUS_OFF = "离线";
|
||||
public static String SIGNAL_STATUS_ERROR = "异常";
|
||||
public static String SIGNAL_STATUS_INIT = "初始导入";
|
||||
|
||||
}
|
|
@ -0,0 +1,331 @@
|
|||
package net.shapelight.modules.app.controller;
|
||||
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.PutObjectOptions;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiImplicitParam;
|
||||
import io.swagger.annotations.ApiImplicitParams;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import net.shapelight.common.config.GlobalValue;
|
||||
import net.shapelight.common.config.MinioConfig;
|
||||
import net.shapelight.common.utils.*;
|
||||
import net.shapelight.modules.app.annotation.Login;
|
||||
import net.shapelight.modules.app.annotation.LoginUser;
|
||||
import net.shapelight.modules.app.entity.AppUserEntity;
|
||||
import net.shapelight.modules.app.entity.AppUserScopeEntity;
|
||||
import net.shapelight.modules.app.service.AppUserScopeService;
|
||||
import net.shapelight.modules.app.service.AppUserService;
|
||||
import net.shapelight.modules.ten.entity.*;
|
||||
import net.shapelight.modules.ten.service.*;
|
||||
import net.shapelight.modules.vo.TenDeviceVo;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* APP测试接口
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/app")
|
||||
@Api("APP接口")
|
||||
public class AppInfoApiController {
|
||||
|
||||
@Autowired
|
||||
private AppUserService appUserService;
|
||||
@Autowired
|
||||
private TenPersonService tenPersonService;
|
||||
@Autowired
|
||||
private TenCellService tenCellService;
|
||||
@Autowired
|
||||
private TenBuildService tenBuildService;
|
||||
@Autowired
|
||||
private TenRoomService tenRoomService;
|
||||
@Autowired
|
||||
private AppUserScopeService appUserScopeService;
|
||||
@Autowired
|
||||
private TenDeviceService tenDeviceService;
|
||||
@Autowired
|
||||
private MinioConfig minioConfig;
|
||||
@Autowired
|
||||
private MinioClient minioClient;
|
||||
@Autowired
|
||||
private TenNoticeService tenNoticeService;
|
||||
@Autowired
|
||||
private TenFeedbackService tenFeedbackService;
|
||||
@Autowired
|
||||
private TenRepairService tenRepairService;
|
||||
@Autowired
|
||||
private GlobalValue globalValue;
|
||||
@Autowired
|
||||
private TenRecordService tenRecordService;
|
||||
@Autowired
|
||||
private TenCellDeptService tenCellDeptService;
|
||||
@Autowired
|
||||
private TenRelationService relationService;
|
||||
|
||||
|
||||
@Login
|
||||
@PostMapping("listNotice")
|
||||
@ApiOperation(value = "查看公告",response = TenNoticeEntity.class)
|
||||
// @ApiImplicitParams({
|
||||
// @ApiImplicitParam(name="cellId",value = "小区",paramType = "query",dataType = "String",required = true)
|
||||
// })
|
||||
public R listNotice(@LoginUser AppUserEntity user, @RequestBody Map<String, Object> params) {
|
||||
if(user == null){
|
||||
return R.error("用户不存在");
|
||||
}
|
||||
AppUserScopeEntity scope = appUserScopeService.getById(user.getCurrentScopeId());
|
||||
Long cellId = scope.getCellId();
|
||||
params.put("cellId",cellId);
|
||||
List<TenNoticeEntity> list = new ArrayList<>();
|
||||
//管理员显示发布时间未到的公告
|
||||
if (scope.getRoleId().intValue() == Constant.ROLE_TEN_CELL) {
|
||||
list = tenNoticeService.list(new QueryWrapper<TenNoticeEntity>()
|
||||
.eq("cell_id",cellId)
|
||||
.orderByDesc("publish_time")
|
||||
.last("LIMIT 10"));
|
||||
}else{
|
||||
//业主显示发不时间到了的公告
|
||||
list = tenNoticeService.list(new QueryWrapper<TenNoticeEntity>()
|
||||
.eq("cell_id",cellId)
|
||||
.le("publish_time",new Date())
|
||||
.orderByDesc("publish_time")
|
||||
.last("LIMIT 10"));
|
||||
}
|
||||
|
||||
return R.ok().put("data",list);
|
||||
}
|
||||
|
||||
|
||||
@Login
|
||||
@PostMapping("listNoticeTop")
|
||||
@ApiOperation(value = "查看公告一条",response = TenNoticeEntity.class)
|
||||
public R listNoticeTop(@LoginUser AppUserEntity user, @RequestBody Map<String, Object> params) {
|
||||
if(user == null){
|
||||
return R.error("用户不存在");
|
||||
}
|
||||
AppUserScopeEntity scope = appUserScopeService.getById(user.getCurrentScopeId());
|
||||
Long cellId = scope.getCellId();
|
||||
params.put("cellId",cellId);
|
||||
List<TenNoticeEntity> list = tenNoticeService.list(new QueryWrapper<TenNoticeEntity>()
|
||||
.eq("cell_id",cellId)
|
||||
.le("publish_time",new Date())
|
||||
.orderByDesc("publish_time")
|
||||
.last("LIMIT 1"));
|
||||
return R.ok().put("data",list);
|
||||
}
|
||||
|
||||
|
||||
@Login
|
||||
@PostMapping("listFeedback")
|
||||
@ApiOperation(value = "查看意见反馈列表",response = TenFeedbackEntity.class)
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "limit", value = "每页条数", paramType = "query", dataType = "String", required = true),
|
||||
@ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "String", required = true),
|
||||
// @ApiImplicitParam(name="cellId",value = "小区",paramType = "query",dataType = "String",required = true)
|
||||
})
|
||||
public R listFeedback(@LoginUser AppUserEntity user, @RequestBody Map<String, Object> params) {
|
||||
if(user == null){
|
||||
return R.error("用户不存在");
|
||||
}
|
||||
AppUserScopeEntity scope = appUserScopeService.getById(user.getCurrentScopeId());
|
||||
Long cellId = scope.getCellId();
|
||||
params.put("cellId",cellId);
|
||||
if(scope.getRoleId() == Constant.ROLE_TEN_CELL){
|
||||
PageUtils page =tenFeedbackService.queryPageByCellAdmin(params);
|
||||
return R.ok().put("data",page);
|
||||
}else{
|
||||
Long personId = scope.getPersonId();
|
||||
params.put("personId",personId);
|
||||
PageUtils page =tenFeedbackService.queryPageByOwner(params);
|
||||
return R.ok().put("data",page);
|
||||
}
|
||||
}
|
||||
|
||||
@Login
|
||||
@PostMapping("listRepair")
|
||||
@ApiOperation(value = "查看报修列表",response = TenRepairEntity.class)
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "limit", value = "每页条数", paramType = "query", dataType = "String", required = true),
|
||||
@ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "String", required = true),
|
||||
// @ApiImplicitParam(name="cellId",value = "小区",paramType = "query",dataType = "String",required = true)
|
||||
})
|
||||
public R listRepair(@LoginUser AppUserEntity user, @RequestBody Map<String, Object> params) {
|
||||
if(user == null){
|
||||
return R.error("用户不存在");
|
||||
}
|
||||
AppUserScopeEntity scope = appUserScopeService.getById(user.getCurrentScopeId());
|
||||
Long cellId = scope.getCellId();
|
||||
params.put("cellId",cellId);
|
||||
if(scope.getRoleId() == Constant.ROLE_TEN_CELL){
|
||||
PageUtils page =tenRepairService.queryPageByCellAdmin(params);
|
||||
return R.ok().put("data",page);
|
||||
}else{
|
||||
Long personId = scope.getPersonId();
|
||||
params.put("personId",personId);
|
||||
PageUtils page =tenRepairService.queryPageByOwner(params);
|
||||
return R.ok().put("data",page);
|
||||
}
|
||||
}
|
||||
|
||||
@Login
|
||||
@PostMapping("/addNotice")
|
||||
@ApiOperation("添加公告")
|
||||
public R addNotice(@LoginUser AppUserEntity user,@RequestBody TenNoticeEntity tenNotice) {
|
||||
if(user == null){
|
||||
return R.error("用户不存在");
|
||||
}
|
||||
AppUserScopeEntity scope = appUserScopeService.getById(user.getCurrentScopeId());
|
||||
Long cellId = scope.getCellId();
|
||||
tenNotice.setCellId(cellId);
|
||||
tenNotice.setCreateBy(user.getUsername());
|
||||
tenNotice.setCreateTime(new Date());
|
||||
tenNoticeService.save(tenNotice);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@Login
|
||||
@PostMapping("addFeedback")
|
||||
@ApiOperation("业主添加意见反馈")
|
||||
// @ApiImplicitParams({
|
||||
// @ApiImplicitParam(name="cellId",value = "小区",paramType = "query",dataType = "String",required = true)
|
||||
// })
|
||||
public R addFeedback(@LoginUser AppUserEntity user, @RequestBody TenFeedbackEntity feedback) {
|
||||
if(user == null){
|
||||
return R.error("用户不存在");
|
||||
}
|
||||
AppUserScopeEntity scope = appUserScopeService.getById(user.getCurrentScopeId());
|
||||
Long cellId = scope.getCellId();
|
||||
feedback.setCellId(cellId);
|
||||
feedback.setFeedbackTime(new Date());
|
||||
tenFeedbackService.save(feedback);
|
||||
return R.ok("您的宝贵意见已经反馈,谢谢!");
|
||||
}
|
||||
|
||||
|
||||
@Login
|
||||
@PostMapping("reviewFeedback")
|
||||
@ApiOperation("管理员回复意见反馈")
|
||||
// @ApiImplicitParams({
|
||||
// @ApiImplicitParam(name="cellId",value = "小区",paramType = "query",dataType = "String",required = true)
|
||||
// })
|
||||
public R reviewFeedback(@LoginUser AppUserEntity user, @RequestBody TenFeedbackEntity feedback) {
|
||||
if(user == null){
|
||||
return R.error("用户不存在");
|
||||
}
|
||||
AppUserScopeEntity scope = appUserScopeService.getById(user.getCurrentScopeId());
|
||||
Long cellId = scope.getCellId();
|
||||
feedback.setCellId(cellId);
|
||||
feedback.setReplyTime(new Date());
|
||||
feedback.setReplyUserName(user.getUsername());
|
||||
tenFeedbackService.updateById(feedback);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
@Login
|
||||
@PostMapping("addRepair")
|
||||
@ApiOperation("业主添加房屋报修")
|
||||
// @ApiImplicitParams({
|
||||
// @ApiImplicitParam(name="cellId",value = "小区",paramType = "query",dataType = "String",required = true)
|
||||
// })
|
||||
public R addRepair(@LoginUser AppUserEntity user, @RequestBody TenRepairEntity repair) {
|
||||
if(user == null){
|
||||
return R.error("用户不存在");
|
||||
}
|
||||
AppUserScopeEntity scope = appUserScopeService.getById(user.getCurrentScopeId());
|
||||
Long cellId = scope.getCellId();
|
||||
repair.setCellId(cellId);
|
||||
repair.setRepairTime(new Date());
|
||||
tenRepairService.save(repair);
|
||||
return R.ok("您的报修申请已经提交,维修人员会尽快联系您!");
|
||||
}
|
||||
|
||||
|
||||
@Login
|
||||
@PostMapping("reviewRepair")
|
||||
@ApiOperation("管理员审批房屋报修")
|
||||
public R reviewRepair(@LoginUser AppUserEntity user, @RequestBody TenRepairEntity repair) {
|
||||
if(user == null){
|
||||
return R.error("用户不存在");
|
||||
}
|
||||
AppUserScopeEntity scope = appUserScopeService.getById(user.getCurrentScopeId());
|
||||
Long cellId = scope.getCellId();
|
||||
repair.setCellId(cellId);
|
||||
repair.setRepairTime(new Date());
|
||||
tenRepairService.updateById(repair);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Login
|
||||
@PostMapping("/openDoorRecordList")
|
||||
@ApiOperation(value = "查询开门记录分页",response = TenRecordEntity.class)
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name="limit",value = "每页条数",paramType = "query",dataType = "String",required = true),
|
||||
@ApiImplicitParam(name="page",value = "页码",paramType = "query",dataType = "String",required = true),
|
||||
@ApiImplicitParam(name="name",value = "姓名",paramType = "query",dataType = "String",required = true),
|
||||
@ApiImplicitParam(name="during",value = "时间段0当天1本周2本月",paramType = "query",dataType = "String",required = true),
|
||||
// @ApiImplicitParam(name="recordTimeStart",value = "开始时间",paramType = "query",dataType = "String",required = true),
|
||||
// @ApiImplicitParam(name="recordTimeEnd",value = "结束时间",paramType = "query",dataType = "String",required = true),
|
||||
})
|
||||
public R openDoorRecordList(@LoginUser AppUserEntity user,@RequestBody Map<String, Object> params){
|
||||
if(user == null){
|
||||
return R.error("用户不存在");
|
||||
}
|
||||
|
||||
AppUserScopeEntity scope = appUserScopeService.getById(user.getCurrentScopeId());
|
||||
TenCellEntity cellEntity = tenCellService.getById(scope.getCellId());
|
||||
if(cellEntity!=null){
|
||||
params.put("cellId",cellEntity.getCellId());
|
||||
int during = Integer.parseInt((String)params.get("during"));
|
||||
String recordTimeStart = null;
|
||||
String recordTimeEnd = null;
|
||||
if(during == 0){ //当天
|
||||
recordTimeStart = MyDateUtils.getCurrentDayStartTime();
|
||||
recordTimeEnd = MyDateUtils.getCurrentDayEndTime();
|
||||
}else if(during == 1){ //本周
|
||||
recordTimeStart = MyDateUtils.getCurrentWeekStartTime();
|
||||
recordTimeEnd = MyDateUtils.getCurrentWeekEndTime();
|
||||
}else if(during == 2){ //本月
|
||||
recordTimeStart = MyDateUtils.getCurrentMonthStartTime();
|
||||
recordTimeEnd = MyDateUtils.getCurrentMonthEndTime();
|
||||
}
|
||||
params.put("recordTimeStart",recordTimeStart);
|
||||
params.put("recordTimeEnd",recordTimeEnd);
|
||||
|
||||
///小区管理员
|
||||
if(scope.getRoleId() == Constant.ROLE_TEN_CELL){
|
||||
params.put("cellId",scope.getCellId().toString());
|
||||
PageUtils page = tenRecordService.queryPage(params);
|
||||
return R.ok().put("data", page);
|
||||
}
|
||||
//业主
|
||||
else if(scope.getRoleId() == Constant.PERSON_TYPE_PARENT){
|
||||
List<TenRelation> relationList = relationService.list(new LambdaQueryWrapper<TenRelation>()
|
||||
.eq(TenRelation::getParentId,user.getUserId()).eq(TenRelation::getStatus,1));
|
||||
if(!relationList.isEmpty()) {
|
||||
List<Long> list = relationList.stream().map(TenRelation::getStudentId).collect(Collectors.toList());
|
||||
params.put("tenantId",user.getTenantId());
|
||||
params.put("personIds",list);
|
||||
PageUtils page = tenRecordService.getByPersonIds(params);
|
||||
return R.ok().put("data", page);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return R.ok().put("data",new PageUtils(new ArrayList<>(),0,0,0));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,101 @@
|
|||
package net.shapelight.modules.app.controller;
|
||||
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import net.shapelight.common.utils.IpUtils;
|
||||
import net.shapelight.common.utils.R;
|
||||
import net.shapelight.common.utils.ServletUtils;
|
||||
import net.shapelight.common.validator.ValidatorUtils;
|
||||
import net.shapelight.modules.app.annotation.Login;
|
||||
import net.shapelight.modules.app.annotation.LoginUser;
|
||||
import net.shapelight.modules.app.entity.AppUserEntity;
|
||||
import net.shapelight.modules.app.form.LoginForm;
|
||||
import net.shapelight.modules.app.service.AppUserService;
|
||||
import net.shapelight.modules.app.utils.JwtUtils;
|
||||
//import net.shapelight.modules.sys.entity.PushEntity;
|
||||
//import net.shapelight.modules.sys.service.PushService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import net.shapelight.modules.ten.entity.TenParent;
|
||||
import net.shapelight.modules.ten.service.TenParentService;
|
||||
import net.shapelight.modules.vo.TokenVo;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* APP登录授权
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/app")
|
||||
@Api("APP登录接口")
|
||||
public class AppLoginController {
|
||||
@Autowired
|
||||
private AppUserService userService;
|
||||
@Autowired
|
||||
private JwtUtils jwtUtils;
|
||||
// @Autowired
|
||||
// PushService pushService;
|
||||
@Autowired
|
||||
TenParentService parentService;
|
||||
|
||||
/**
|
||||
* 登录
|
||||
*/
|
||||
@PostMapping("login")
|
||||
@ApiOperation("登录")
|
||||
public R login(@RequestBody LoginForm form){
|
||||
//表单校验
|
||||
ValidatorUtils.validateEntity(form);
|
||||
//用户登录
|
||||
AppUserEntity user = userService.login(form);
|
||||
//生成token
|
||||
String token = jwtUtils.generateToken(user.getUserId());
|
||||
TokenVo tokenVo = new TokenVo();
|
||||
tokenVo.setToken(token);
|
||||
tokenVo.setExpire((int)jwtUtils.getExpire());
|
||||
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
|
||||
user.setLoginTime(new Date());
|
||||
user.setLoginIp(ip);
|
||||
userService.saveOrUpdate(user);
|
||||
return R.ok().put("data",tokenVo);
|
||||
|
||||
}
|
||||
/*
|
||||
* Token登陆
|
||||
*/
|
||||
@Login
|
||||
@GetMapping("checkin")
|
||||
@ApiOperation("获取用户信息")
|
||||
public R userInfo(@LoginUser AppUserEntity user){
|
||||
// if(user == null){
|
||||
// return R.error(401,"用户不存在");
|
||||
// }
|
||||
if(user == null){
|
||||
return R.error("用户不存在");
|
||||
}
|
||||
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
|
||||
user.setLoginTime(new Date());
|
||||
user.setLoginIp(ip);
|
||||
TenParent parent = parentService.getOne(new LambdaQueryWrapper<TenParent>().eq(TenParent::getUserId,user.getUserId()));
|
||||
user.setParent(parent);
|
||||
userService.saveOrUpdate(user);
|
||||
return R.ok().put("data", user);
|
||||
}
|
||||
|
||||
// @Login
|
||||
// @PostMapping("logout")
|
||||
// @ApiOperation("退出登陆")
|
||||
// //public R updateMobile(@LoginUser UserEntity user,HttpServletRequest request,String mobile, String password,String smscode){
|
||||
// public R logout(HttpServletRequest request, @LoginUser AppUserEntity user){
|
||||
// //删除这个用户的rid
|
||||
// String token = request.getHeader("token");
|
||||
//// pushService.deleteFromToken(token);
|
||||
// return R.ok();
|
||||
// }
|
||||
|
||||
}
|
|
@ -0,0 +1,270 @@
|
|||
package net.shapelight.modules.app.controller;
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
//import net.shapelight.common.utils.AliyunSmsUtils;
|
||||
import io.swagger.annotations.ApiImplicitParam;
|
||||
import io.swagger.annotations.ApiImplicitParams;
|
||||
import net.shapelight.common.utils.R;
|
||||
import net.shapelight.common.utils.RedisUtils;
|
||||
import net.shapelight.common.validator.ValidatorUtils;
|
||||
import net.shapelight.modules.app.annotation.Login;
|
||||
import net.shapelight.modules.app.annotation.LoginUser;
|
||||
import net.shapelight.modules.app.entity.AppUserEntity;
|
||||
import net.shapelight.modules.app.form.RegisterForm;
|
||||
//import net.shapelight.modules.sys.entity.BindEntity;
|
||||
//import net.shapelight.modules.sys.service.BindService;
|
||||
//import net.shapelight.modules.sys.service.PushService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import net.shapelight.modules.app.service.AppUserService;
|
||||
import net.shapelight.modules.app.utils.MonyunSmsUtils;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 注册
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/app")
|
||||
@Api("APP注册接口")
|
||||
public class AppRegisterController {
|
||||
@Autowired
|
||||
private AppUserService userService;
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Autowired
|
||||
private HttpServletResponse httpServletResponse;
|
||||
@Autowired
|
||||
private RedisUtils redisUtils;
|
||||
|
||||
|
||||
@PostMapping("sendsms")
|
||||
@ApiOperation("获取验证码")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "mobile", value = "手机号", paramType = "query", dataType = "String", required = true),
|
||||
@ApiImplicitParam(name = "type", value = "类型1注册2忘记密码", paramType = "query", dataType = "String", required = true)
|
||||
})
|
||||
public R sendsms(@RequestBody Map<String, Object> params) {
|
||||
//验证手机是否注册
|
||||
String mobile = (String) params.get("mobile");
|
||||
int type = (Integer) params.get("type");
|
||||
//type=1 //注册
|
||||
//type=2 //忘记密码
|
||||
//type=1 //修改绑定的手机
|
||||
if (type == 1) {//注册//修改绑定的手机
|
||||
AppUserEntity user = userService.findByMobile(mobile);
|
||||
if (user != null) {
|
||||
return R.error("手机号码已注册");
|
||||
}
|
||||
} else if (type == 2) {//忘记密码
|
||||
AppUserEntity user = userService.findByMobile(mobile);
|
||||
if (user == null) {
|
||||
return R.error("当前手机号未被使用");
|
||||
}
|
||||
} else {
|
||||
return R.error("未知类型");
|
||||
}
|
||||
String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
|
||||
int result = MonyunSmsUtils.sendSms(mobile, verifyCode);
|
||||
Map<String, Object> resMap = new HashMap<>();
|
||||
resMap.put("result", result);
|
||||
if (result != 0) {
|
||||
return R.error(result+"");
|
||||
}
|
||||
redisUtils.set(mobile,verifyCode,120L);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
// @PostMapping("register")
|
||||
// public R register(@RequestBody Map<String, Object> map) {
|
||||
// String mobile = (String) map.get("mobile");
|
||||
// String password = (String) map.get("password");
|
||||
// String smscode = (String) map.get("smscode");
|
||||
//
|
||||
// JSONObject SessionJson = (JSONObject) request.getSession().getAttribute("verifyCode");
|
||||
//
|
||||
// if (SessionJson == null) {
|
||||
// return R.error("请先发送验证码");
|
||||
// }
|
||||
// String s_msg_id = SessionJson.getString("msg_id");
|
||||
// String s_mobile = SessionJson.getString("mobile");
|
||||
// String verifyCode = SessionJson.getString("verifyCode");
|
||||
//
|
||||
// if (!verifyCode.equals(smscode)) {
|
||||
// return R.error("验证码错误");
|
||||
// }
|
||||
//
|
||||
// AppUserEntity user = new AppUserEntity();
|
||||
// user.setMobile(mobile);
|
||||
// user.setUsername(mobile);
|
||||
// user.setPassword(DigestUtils.sha256Hex(password));
|
||||
// user.setCreateTime(new Date());
|
||||
// userService.save(user);
|
||||
// request.getSession().setAttribute("verifyCode", null);
|
||||
// return R.ok();
|
||||
// }
|
||||
|
||||
@PostMapping("checkCode")
|
||||
@ApiOperation("检测验证码")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "mobile", value = "手机号", paramType = "query", dataType = "String", required = true),
|
||||
@ApiImplicitParam(name = "smscode", value = "验证码", paramType = "query", dataType = "String", required = true)
|
||||
})
|
||||
public R checkCode(@RequestBody Map<String, Object> map) {
|
||||
String mobile = (String) map.get("mobile");
|
||||
String smscode = (String) map.get("smscode");
|
||||
|
||||
// JSONObject SessionJson = (JSONObject) request.getSession().getAttribute("verifyCode");
|
||||
|
||||
String verifyCode = (String)redisUtils.get(mobile);
|
||||
|
||||
// if (SessionJson == null) {
|
||||
// return R.error("请先发送验证码");
|
||||
// }
|
||||
// String s_msg_id = SessionJson.getString("msg_id");
|
||||
// String s_mobile = SessionJson.getString("mobile");
|
||||
// String verifyCode = SessionJson.getString("verifyCode");
|
||||
// String rMobile = SessionJson.getString("mobile");
|
||||
|
||||
if (verifyCode!=null && !verifyCode.equals(smscode)) {
|
||||
return R.error("验证码错误");
|
||||
}
|
||||
|
||||
if (verifyCode == null){
|
||||
return R.error("验证码已过期");
|
||||
}
|
||||
// if (!rMobile.equals(mobile)) {
|
||||
// return R.error("请输入验证码对应的手机号");
|
||||
// }
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
@PostMapping("forgetPassword")
|
||||
@ApiOperation("忘记密码重置密码")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "mobile", value = "手机号", paramType = "query", dataType = "String", required = true),
|
||||
@ApiImplicitParam(name = "password", value = "密码", paramType = "query", dataType = "String", required = true),
|
||||
@ApiImplicitParam(name = "smscode", value = "验证码", paramType = "query", dataType = "String", required = true)
|
||||
})
|
||||
public R forgetPassword(HttpServletRequest request, @RequestBody Map<String, Object> map) {
|
||||
String mobile = (String) map.get("mobile");
|
||||
String password = (String) map.get("password");
|
||||
// String smscode = (String) map.get("smscode");
|
||||
|
||||
// JSONObject SessionJson = (JSONObject) request.getSession().getAttribute("verifyCode");
|
||||
|
||||
// if (SessionJson == null) {
|
||||
// return R.error("请先发送验证吗");
|
||||
// }
|
||||
// String s_msg_id = SessionJson.getString("msg_id");
|
||||
// String s_mobile = SessionJson.getString("mobile");
|
||||
// String verifyCode = SessionJson.getString("verifyCode");
|
||||
//
|
||||
// if (!verifyCode.equals(smscode)) {
|
||||
// return R.error("验证码错误");
|
||||
// }
|
||||
|
||||
AppUserEntity user = userService.findByMobile(mobile);
|
||||
user.setPassword(DigestUtils.sha256Hex(password));
|
||||
userService.saveOrUpdate(user);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
@Login
|
||||
@PostMapping("updatePassword")
|
||||
@ApiOperation("修改密码")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "oldPassword", value = "旧密码", paramType = "query", dataType = "String", required = true),
|
||||
@ApiImplicitParam(name = "newPassword", value = "新密码", paramType = "query", dataType = "String", required = true),
|
||||
})
|
||||
//public R updatePassword(@LoginUser UserEntity user, String oldPassword,String newPassword){
|
||||
public R updatePassword(@LoginUser AppUserEntity user, @RequestBody Map<String, Object> map) {
|
||||
if(user == null){
|
||||
return R.error("用户不存在");
|
||||
}
|
||||
String oldPassword = (String) map.get("oldPassword");
|
||||
String newPassword = (String) map.get("newPassword");
|
||||
if (user.getPassword().equals(DigestUtils.sha256Hex(oldPassword))) {
|
||||
user.setPassword(DigestUtils.sha256Hex(newPassword));
|
||||
if (oldPassword.equals(newPassword)) {
|
||||
return R.error("新密码和旧密码不能相同");
|
||||
}
|
||||
userService.saveOrUpdate(user);
|
||||
return R.ok();
|
||||
} else {
|
||||
return R.error("初始密码不正确");
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
@Login
|
||||
@PostMapping("updateMobile")
|
||||
@ApiOperation("修改绑定的手机")
|
||||
public R updateMobile(@LoginUser UserEntity user,HttpServletRequest request,@RequestBody Map<String, Object> map){
|
||||
String oldMoblie = user.getMobile();
|
||||
int delFlag = 0;
|
||||
String mobile = (String)map.get("mobile");
|
||||
String password = (String)map.get("password");
|
||||
String smscode = (String)map.get("smscode");
|
||||
|
||||
JSONObject SessionJson = (JSONObject)request.getSession().getAttribute("verifyCode");
|
||||
|
||||
if(SessionJson==null) {
|
||||
return R.error("请先发送验证吗");
|
||||
}
|
||||
String s_msg_id = SessionJson.getString("msg_id");
|
||||
String s_mobile = SessionJson.getString("mobile");
|
||||
String res = JSMSUtil.sendValidSMSCode(s_msg_id,smscode);
|
||||
if(res.equals("")){
|
||||
return R.error("无法验证");
|
||||
}
|
||||
|
||||
JSONObject vjson = JSONObject.parseObject(res);
|
||||
boolean valid = vjson.getBoolean("is_valid");
|
||||
if(!valid){
|
||||
String err_msg = JSONObject.parseObject(vjson.getString("error")).getString("message");
|
||||
return R.error("验证码错误");
|
||||
}
|
||||
|
||||
if(user.getPassword().equals(DigestUtils.sha256Hex(password))) {
|
||||
//将用户信息存入数据库
|
||||
user.setMobile(mobile);
|
||||
user.setUsername(mobile);
|
||||
user.setPassword(DigestUtils.sha256Hex(password));
|
||||
user.setCreateTime(new Date());
|
||||
userService.saveOrUpdate(user);
|
||||
|
||||
|
||||
List<BindEntity> bl = bindService.queryByMoblie(oldMoblie,delFlag);
|
||||
for(int i = 0;i<bl.size();i++){
|
||||
BindEntity b = bl.get(i);
|
||||
BindEntity be = bindService.checkBind(b.getDevImei(),mobile,delFlag);
|
||||
if(be == null){
|
||||
b.setUserMobile(mobile);
|
||||
bindService.saveOrUpdate(b);
|
||||
}else{
|
||||
|
||||
}
|
||||
}
|
||||
return R.ok();
|
||||
}else {
|
||||
return R.error("密码不正确");
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
//---------------------------------aliiyun-------------------
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package net.shapelight.modules.app.controller;
|
||||
|
||||
|
||||
import net.shapelight.common.utils.R;
|
||||
import net.shapelight.modules.app.annotation.Login;
|
||||
import net.shapelight.modules.app.annotation.LoginUser;
|
||||
import net.shapelight.modules.app.entity.AppUserEntity;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* APP测试接口
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/app")
|
||||
//@Api("APP测试接口")
|
||||
public class AppTestController {
|
||||
|
||||
@Login
|
||||
@GetMapping("userInfo")
|
||||
// @ApiOperation("获取用户信息")
|
||||
public R userInfo(@LoginUser AppUserEntity user){
|
||||
return R.ok().put("user", user);
|
||||
}
|
||||
|
||||
|
||||
@Login
|
||||
@GetMapping("userId")
|
||||
// @ApiOperation("获取用户ID")
|
||||
public R userInfo(@RequestAttribute("userId") Integer userId){
|
||||
return R.ok().put("userId", userId);
|
||||
}
|
||||
|
||||
|
||||
@GetMapping("notToken")
|
||||
// @ApiOperation("忽略Token验证测试")
|
||||
public R notToken(){
|
||||
return R.ok().put("msg", "无需token也能访问。。。");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package net.shapelight.modules.app.controller;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.shiro.authz.annotation.RequiresPermissions;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import net.shapelight.modules.app.entity.AppUserEntity;
|
||||
import net.shapelight.modules.app.service.AppUserService;
|
||||
import net.shapelight.common.utils.PageUtils;
|
||||
import net.shapelight.common.utils.R;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* App用户
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("app/user")
|
||||
public class AppUserController {
|
||||
@Autowired
|
||||
private AppUserService appUserService;
|
||||
|
||||
/**
|
||||
* 列表
|
||||
*/
|
||||
@RequestMapping("/list")
|
||||
@RequiresPermissions("app:user:list")
|
||||
public R list(@RequestParam Map<String, Object> params){
|
||||
PageUtils page = appUserService.queryPage(params);
|
||||
|
||||
return R.ok().put("page", page);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 信息
|
||||
*/
|
||||
@RequestMapping("/info/{userId}")
|
||||
@RequiresPermissions("app:user:info")
|
||||
public R info(@PathVariable("userId") Long userId){
|
||||
AppUserEntity appUser = appUserService.getById(userId);
|
||||
|
||||
return R.ok().put("appUser", appUser);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存
|
||||
*/
|
||||
@RequestMapping("/save")
|
||||
@RequiresPermissions("app:user:save")
|
||||
public R save(@RequestBody AppUserEntity appUser){
|
||||
appUserService.save(appUser);
|
||||
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改
|
||||
*/
|
||||
@RequestMapping("/update")
|
||||
@RequiresPermissions("app:user:update")
|
||||
public R update(@RequestBody AppUserEntity appUser){
|
||||
appUserService.updateById(appUser);
|
||||
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除
|
||||
*/
|
||||
@RequestMapping("/delete")
|
||||
@RequiresPermissions("app:user:delete")
|
||||
public R delete(@RequestBody Long[] userIds){
|
||||
appUserService.removeByIds(Arrays.asList(userIds));
|
||||
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package net.shapelight.modules.app.controller;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.shiro.authz.annotation.RequiresPermissions;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import net.shapelight.modules.app.entity.AppUserScopeEntity;
|
||||
import net.shapelight.modules.app.service.AppUserScopeService;
|
||||
import net.shapelight.common.utils.PageUtils;
|
||||
import net.shapelight.common.utils.R;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 用户小区表
|
||||
*
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("ten/appuserscope")
|
||||
public class AppUserScopeController {
|
||||
@Autowired
|
||||
private AppUserScopeService appUserScopeService;
|
||||
|
||||
/**
|
||||
* 列表
|
||||
*/
|
||||
@RequestMapping("/list")
|
||||
@RequiresPermissions("ten:appuserscope:list")
|
||||
public R list(@RequestParam Map<String, Object> params){
|
||||
PageUtils page = appUserScopeService.queryPage(params);
|
||||
|
||||
return R.ok().put("page", page);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 信息
|
||||
*/
|
||||
@RequestMapping("/info/{userScopeId}")
|
||||
@RequiresPermissions("ten:appuserscope:info")
|
||||
public R info(@PathVariable("userScopeId") Long userScopeId){
|
||||
AppUserScopeEntity appUserScope = appUserScopeService.getById(userScopeId);
|
||||
|
||||
return R.ok().put("appUserScope", appUserScope);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存
|
||||
*/
|
||||
@RequestMapping("/save")
|
||||
@RequiresPermissions("ten:appuserscope:save")
|
||||
public R save(@RequestBody AppUserScopeEntity appUserScope){
|
||||
appUserScopeService.save(appUserScope);
|
||||
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改
|
||||
*/
|
||||
@RequestMapping("/update")
|
||||
@RequiresPermissions("ten:appuserscope:update")
|
||||
public R update(@RequestBody AppUserScopeEntity appUserScope){
|
||||
appUserScopeService.updateById(appUserScope);
|
||||
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除
|
||||
*/
|
||||
@RequestMapping("/delete")
|
||||
@RequiresPermissions("ten:appuserscope:delete")
|
||||
public R delete(@RequestBody Long[] userScopeIds){
|
||||
appUserScopeService.removeByIds(Arrays.asList(userScopeIds));
|
||||
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package net.shapelight.modules.app.controller;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class ResponseVo implements Serializable {
|
||||
|
||||
|
||||
private static final long serialVersionUID = -6731480716359757287L;
|
||||
|
||||
private Object data;
|
||||
private int code = 200;
|
||||
private String message;
|
||||
|
||||
|
||||
public static ResponseVo getInstance() {
|
||||
|
||||
return new ResponseVo();
|
||||
}
|
||||
|
||||
|
||||
public Object getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(Object data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public static long getSerialVersionUID() {
|
||||
return serialVersionUID;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue