Commit 25a6e18a by 梁家彪

初始化项目

parents

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="model-server" />
<module name="config-server" />
<module name="spider-flow-api" />
<module name="spider-flow-core" />
<module name="spider-flow-selenium" />
<module name="gateway-server" />
<module name="spider-flow-web" />
<module name="sys-server" />
<module name="eureka-server" />
</profile>
</annotationProcessing>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="config-server" options="-parameters" />
<module name="eureka-server" options="-parameters" />
<module name="gateway-server" options="-parameters" />
<module name="model-server" options="-parameters" />
<module name="spider-flow-api" options="-parameters" />
<module name="spider-flow-core" options="-parameters" />
<module name="spider-flow-selenium" options="-parameters" />
<module name="spider-flow-web" options="-parameters" />
<module name="sys-server" options="-parameters" />
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/config-server/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/eureka-server/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/gateway-server/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/model-server/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/spider-flow-api/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/spider-flow-core/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/spider-flow-selenium/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/spider-flow-web/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/sys-server/src/main/java" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="http://maven.aliyun.com/nexus/content/repositories/central/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="nexus" />
<option name="name" value="Repository for nexus" />
<option name="url" value="http://129.204.37.121:8081/repository/maven-public/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="corretto-1.8" project-jdk-type="JavaSDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="2bdb0347-1bf3-4703-b530-9af8159bcbf0" name="Changes" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="MavenImportPreferences">
<option name="generalSettings">
<MavenGeneralSettings>
<option name="mavenHome" value="$PROJECT_DIR$/../../apache-maven-3.6.3" />
<option name="useMavenConfig" value="true" />
<option name="userSettingsFile" value="D:\apache-maven-3.6.3\conf\settings.xml" />
</MavenGeneralSettings>
</option>
<option name="enabledProfiles">
<list>
<option value="test" />
</list>
</option>
<option name="disabledProfiles">
<list>
<option value="nexus" />
<option value="dev" />
</list>
</option>
</component>
<component name="ProjectId" id="2RmzUSL53TKdmtJlpOsBujEJYO9" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"RequestMappingsPanelOrder0": "0",
"RequestMappingsPanelOrder1": "1",
"RequestMappingsPanelWidth0": "75",
"RequestMappingsPanelWidth1": "75",
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"WebServerToolWindowFactoryState": "false",
"last_opened_file_path": "D:/Java Project/nnjcy-data-model",
"project.structure.last.edited": "Modules",
"project.structure.proportion": "0.15",
"project.structure.side.proportion": "0.24712643",
"settings.editor.selected.configurable": "preferences.fileTypes",
"spring.configuration.checksum": "650583fa4142879cf23e291602e4bb06"
}
}]]></component>
<component name="RunDashboard">
<option name="configurationTypes">
<set>
<option value="SpringBootApplicationConfigurationType" />
</set>
</option>
</component>
<component name="RunManager" selected="Spring Boot.ConfigApplication">
<configuration name="ConfigApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="config-server" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.zq.ConfigApplication" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="EurekaApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="eureka-server" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.zq.EurekaApplication" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="GatewayApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="gateway-server" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.zq.gateway.GatewayApplication" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="ModelApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="model-server" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.zq.model.ModelApplication" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="SpiderApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="spider-flow-web" />
<option name="SPRING_BOOT_MAIN_CLASS" value="org.spiderflow.SpiderApplication" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="SysApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="sys-server" />
<option name="SPRING_BOOT_MAIN_CLASS" value="com.zq.system.SysApplication" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="2bdb0347-1bf3-4703-b530-9af8159bcbf0" name="Changes" comment="" />
<created>1687870060654</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1687870060654</updated>
<workItem from="1687870061985" duration="1654000" />
<workItem from="1687871747633" duration="208000" />
</task>
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.zq</groupId>
<artifactId>nnjcy-data-model</artifactId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>config-client</artifactId>
<name>config-server</name>
<description>Spring Cloud Config Center</description>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
package com.zq;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableDiscoveryClient
@EnableConfigServer
@SpringBootApplication
@EnableEurekaClient
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
server:
port: 8300
spring:
application:
name: CONFIG-SERVER
profiles:
active: native # 配置使用本地储存
cloud:
config:
server:
native:
search-locations: classpath:/properties # 搜索src/main/resource 下的properties文件夹下的文件
# git:
# uri: https://repo.dakatech.cn/repository/projectData.git #配置git仓库的地址
# username: admin@dakatech.cn
# password: Dk2019123456
# search-paths: config-files #配置git仓库下的相对地址,可以配置多个,用 , 分割
eureka:
instance:
prefer-ip-address: true # 使用IP注册服务
lease-renewal-interval-in-seconds: 2 #每间隔1s,向服务端发送一次心跳,证明自己依然"存活"
lease-expiration-duration-in-seconds: 6 #告诉服务端,如果我2s之内没有给你发心跳,就代表我"死"了,将我踢出掉。
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
client:
serviceUrl:
defaultZone: http://admin:123456@127.0.0.1:8800/eureka/
management:
endpoints:
web:
exposure:
include: "*"
#Spring Cloud Config也提供本地存储配置的方式。
#我们只需要设置属性spring.profiles.active: native,Config Server会默认从应用的src/main/resource目录下检索配置文件。
#也可以通过spring.cloud.config.server.native.searchLocations: file:E:/properties/属性来指定配置文件的位置。
#虽然Spring Cloud Config提供了这样的功能,但是为了支持更好的管理内容和版本控制的功能,还是推荐使用git的方式。
gateway.port: 9888
gateway.name: GATEWAY-SERVER
sys.port: 9000
sys.name: SYS-SERVER
file.port: 9500
file.name: FILE-SERVER
spider.port: 8088
spider.name: SPIDER-FLOW
model.port: 9877
model.name: MODEL-SERVER
redis.url: 127.0.0.1
redis.port: 6379
redis.password:
#数据库源配置
jdbc.driver-class-name: com.mysql.cj.jdbc.Driver
jdbc.username: root
jdbc.password: Dk2019!23456
jdbc.url: jdbc:mysql://47.107.148.53:3306/nnjcy_data_model?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&autoReconnct=true
spring:
servlet:
multipart:
# 设置 上传文件的大小
max-file-size: 1024MB
# 设置 整个请求的大小
max-request-size: 2048MB
\ No newline at end of file
gateway.port: 9888
gateway.name: GATEWAY-SERVER
sys.port: 9000
sys.name: SYS-SERVER
file.port: 9500
file.name: FILE-SERVER
spider.port: 8088
spider.name: SPIDER-FLOW
model.port: 9877
model.name: MODEL-SERVER
redis.url: 127.0.0.1
redis.port: 6379
redis.password:
#数据库源配置
jdbc.driver-class-name: com.mysql.cj.jdbc.Driver
jdbc.username: root
jdbc.password: root
jdbc.url: jdbc:mysql://127.0.0.1:3306/nnjcy_data_model?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&autoReconnct=true
spring:
servlet:
multipart:
# 设置 上传文件的大小
max-file-size: 1024MB
# 设置 整个请求的大小
max-request-size: 2048MB
\ No newline at end of file
gateway.port: 9888
gateway.name: GATEWAY-SERVER
sys.port: 9000
sys.name: SYS-SERVER
file.port: 9500
file.name: FILE-SERVER
spider.port: 8088
spider.name: SPIDER-FLOW
model.port: 9877
model.name: MODEL-SERVER
redis.url: 127.0.0.1
redis.port: 6379
redis.password:
#数据库源配置
jdbc.driver-class-name: com.mysql.cj.jdbc.Driver
jdbc.username: root
jdbc.password: root
jdbc.url: jdbc:mysql://127.0.0.1:3306/nnjcy_data_model?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&autoReconnct=true
spring:
servlet:
multipart:
# 设置 上传文件的大小
max-file-size: 1024MB
# 设置 整个请求的大小
max-request-size: 2048MB
\ No newline at end of file
server:
port: 8300
spring:
application:
name: CONFIG-SERVER
profiles:
active: native # 配置使用本地储存
cloud:
config:
server:
native:
search-locations: classpath:/properties # 搜索src/main/resource 下的properties文件夹下的文件
# git:
# uri: https://repo.dakatech.cn/repository/projectData.git #配置git仓库的地址
# username: admin@dakatech.cn
# password: Dk2019123456
# search-paths: config-files #配置git仓库下的相对地址,可以配置多个,用 , 分割
eureka:
instance:
prefer-ip-address: true # 使用IP注册服务
lease-renewal-interval-in-seconds: 2 #每间隔1s,向服务端发送一次心跳,证明自己依然"存活"
lease-expiration-duration-in-seconds: 6 #告诉服务端,如果我2s之内没有给你发心跳,就代表我"死"了,将我踢出掉。
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
client:
serviceUrl:
defaultZone: http://admin:123456@127.0.0.1:8800/eureka/
management:
endpoints:
web:
exposure:
include: "*"
#Spring Cloud Config也提供本地存储配置的方式。
#我们只需要设置属性spring.profiles.active: native,Config Server会默认从应用的src/main/resource目录下检索配置文件。
#也可以通过spring.cloud.config.server.native.searchLocations: file:E:/properties/属性来指定配置文件的位置。
#虽然Spring Cloud Config提供了这样的功能,但是为了支持更好的管理内容和版本控制的功能,还是推荐使用git的方式。
gateway.port: 9888
gateway.name: GATEWAY-SERVER
sys.port: 9000
sys.name: SYS-SERVER
file.port: 9500
file.name: FILE-SERVER
spider.port: 8088
spider.name: SPIDER-FLOW
model.port: 9877
model.name: MODEL-SERVER
redis.url: 127.0.0.1
redis.port: 6379
redis.password:
#数据库源配置
jdbc.driver-class-name: com.mysql.cj.jdbc.Driver
jdbc.username: root
jdbc.password: Dk2019!23456
jdbc.url: jdbc:mysql://47.107.148.53:3306/nnjcy_data_model?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&autoReconnct=true
spring:
servlet:
multipart:
# 设置 上传文件的大小
max-file-size: 1024MB
# 设置 整个请求的大小
max-request-size: 2048MB
\ No newline at end of file
gateway.port: 9888
gateway.name: GATEWAY-SERVER
sys.port: 9000
sys.name: SYS-SERVER
file.port: 9500
file.name: FILE-SERVER
spider.port: 8088
spider.name: SPIDER-FLOW
model.port: 9877
model.name: MODEL-SERVER
redis.url: 127.0.0.1
redis.port: 6379
redis.password:
#数据库源配置
jdbc.driver-class-name: com.mysql.cj.jdbc.Driver
jdbc.username: root
jdbc.password: root
jdbc.url: jdbc:mysql://127.0.0.1:3306/nnjcy_data_model?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&autoReconnct=true
spring:
servlet:
multipart:
# 设置 上传文件的大小
max-file-size: 1024MB
# 设置 整个请求的大小
max-request-size: 2048MB
\ No newline at end of file
gateway.port: 9888
gateway.name: GATEWAY-SERVER
sys.port: 9000
sys.name: SYS-SERVER
file.port: 9500
file.name: FILE-SERVER
spider.port: 8088
spider.name: SPIDER-FLOW
model.port: 9877
model.name: MODEL-SERVER
redis.url: 127.0.0.1
redis.port: 6379
redis.password:
#数据库源配置
jdbc.driver-class-name: com.mysql.cj.jdbc.Driver
jdbc.username: root
jdbc.password: root
jdbc.url: jdbc:mysql://127.0.0.1:3306/nnjcy_data_model?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&autoReconnct=true
spring:
servlet:
multipart:
# 设置 上传文件的大小
max-file-size: 1024MB
# 设置 整个请求的大小
max-request-size: 2048MB
\ No newline at end of file
version=1.0.0
groupId=com.zq
artifactId=config-client
D:\Java Project\nnjcy-data-model\config-server\src\main\java\com\zq\ConfigApplication.java
## 搭建注册中心
### 1.在注册中心服务的pom.xml导入依赖
```
<parent>
<groupId>com.zkane</groupId>
<artifactId>spring-cloud-demo</artifactId>
<version>1.0.0</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
```
### 2.在application.yml文件中配置
```
server:
port: 8000
spring:
application:
name: eureka-server
eureka:
client:
# 表示是否将自己注册到Eureka Server,默认为true。
register-with-eureka: false
# 表示是否从Eureka Server获取注册信息,默认为true。
fetch-registry: false
# 设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址。默认是http://127.0.0.1:8761/eureka ;多个地址可使用,分隔
service-url:
defaultZone: http://127.0.0.1:${server.port}/eureka/
```
### 3.在启动类上配置注解:@EnableEurekaServer
```
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
```
### 4.开启密码认证
- 导入spring security的依赖jar包
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
- 在application.yml中配置用户名和密码
```yaml
spring:
security:
user:
name: admin
password: 123456
```
- 编写一个安全配置类,不然其他服务在启动时会报错`Cannot execute request on any known server`
```java
package com.zkane.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @author: 594781919@qq.com
* @review:
* @date: 2018/8/23
*/
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
```
- 在其他服务配置注册中心
> admin为用户名,123456为密码
```yaml
eureka:
client:
service-url:
defaultZone: http://admin:123456@localhost:8000/eureka/
```
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.zq</groupId>
<artifactId>nnjcy-data-model</artifactId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>eureka-server</artifactId>
<name>eureka-server</name>
<description>Spring Cloud Eureka Server</description>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
</dependencies>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.zq;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
package com.zq.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @author: 594781919@qq.com
* @review:
* @date: 2018/8/23
*/
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
\ No newline at end of file
server:
port: 8800
spring:
application:
name: eureka-server
security:
user:
name: admin
password: 123456
eureka:
instance:
hostname: 127.0.0.1
client:
# 表示是否将自己注册到Eureka Server,默认为true。
register-with-eureka: false
# 表示是否从Eureka Server获取注册信息,默认为true。
fetch-registry: false
# 设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址。默认是http://127.0.0.1:8000/eureka ;多个地址可使用,分隔
service-url:
defaultZone: http://admin:123456@127.0.0.1:8800/eureka/
\ No newline at end of file
package com.zq;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EurekaApplicationTestKit {
@Test
public void contextLoads() {
}
}
server:
port: 8800
spring:
application:
name: eureka-server
security:
user:
name: admin
password: 123456
eureka:
instance:
hostname: 127.0.0.1
client:
# 表示是否将自己注册到Eureka Server,默认为true。
register-with-eureka: false
# 表示是否从Eureka Server获取注册信息,默认为true。
fetch-registry: false
# 设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址。默认是http://127.0.0.1:8000/eureka ;多个地址可使用,分隔
service-url:
defaultZone: http://admin:123456@127.0.0.1:8800/eureka/
\ No newline at end of file
version=1.0.0
groupId=com.zq
artifactId=eureka-server
com\zq\config\WebSecurityConfig.class
com\zq\EurekaApplication.class
D:\Java Project\nnjcy-data-model\eureka-server\src\main\java\com\zq\config\WebSecurityConfig.java
D:\Java Project\nnjcy-data-model\eureka-server\src\main\java\com\zq\EurekaApplication.java
D:\Java Project\nnjcy-data-model\eureka-server\src\test\java\com\zq\EurekaApplicationTestKit.java
## 搭建服务提供者
### 1. 在pom.xml文件中导入依赖
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zkane</groupId>
<artifactId>producer-server</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>producer-server</name>
<description>Spring Cloud Producer Server</description>
<parent>
<groupId>com.zkane</groupId>
<artifactId>spring-cloud-demo</artifactId>
<version>1.0.0</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
```
### 2. 在application.yml配置文件中配置
```
server:
port: 8100
spring:
application:
name: producer-server
eureka:
client:
serviceUrl:
defaultZone: http://127.0.0.1:8000/eureka/
```
### 3. 在启动类上添加注解:@EnableDiscoveryClient
```
@EnableDiscoveryClient
@SpringBootApplication
public class ProducerServerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerServerApplication.class, args);
}
}
```
### 4. 编写controller代码,提供restful风格的API访问
```
@RestController
public class ProducerController {
@Value("${server.port}")
private String port;
@GetMapping("/")
public String get() {
return "Producer Server port: " + port;
}
}
```
### 5.可以修改yml配置文件的端口设置,启动多个服务来测试负载均衡
例如,先启动8100端口的服务,然后修改端口为8101再进行启动。
idea启动多个服务需要设置run/debug configurations,去掉勾选Single instance only
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.zq</groupId>
<artifactId>nnjcy-data-model</artifactId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>gateway-server</artifactId>
<name>gateway-server</name>
<description>Spring Cloud Gateway Server</description>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<!--开启过滤,用指定的参数替换directory下的文件中的参数-->
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
package com.zq.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
server:
port: ${gateway.port}
spring:
application:
name: ${gateway.name}
cloud:
gateway:
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Origin, RETAIN_UNIQUE
discovery:
locator:
enabled: true
globalcors:
cors-configurations:
'[/**]':
allowCredentials: true
allowedOrigins: "*"
allowedMethods: "PUT, POST, GET, OPTIONS, DELETE"
allowedHeaders: "Content-type, Authorization"
maxAge: 3600
routes:
- id: api
uri: lb://${api.name}
predicates:
- Path=/api/**
# filters:
#过滤器 设置所有的 方法都会自动添加foo=bar
# - AddRequestParameter=key, bar
#当请求路径匹配到/hello/world/HiController/**会将包含hello和后边的字符串接去掉转发,
#StripPrefix=2就代表截取路径的个数,这样配置后当请求/hello/world/HiController/aaa后端匹配到的请求路径,
#就会变成http://127.0.0.1:8762/HiController/aaa
# - StripPrefix=2
- id: auth
uri: lb://${auth.name}
predicates:
- Path=/auth/**
- id: sys
uri: lb://${sys.name}
predicates:
- Path=/sys/**
- id: instrument
uri: lb://${instrument.name}
predicates:
- Path=/instrument/**
- id: file
uri: lb://${file.name}
predicates:
- Path=/images/**, /file/**
- id: solr
uri: lb://${solr.name}
predicates:
- Path=/solr/**
- id: spider
uri: lb://${spider.name}
predicates:
- Path=/spider/**
- id: docstat
uri: lb://${stat.name}
predicates:
- Path=/docstat/**
- id: stat
uri: lb://${stat.name}
predicates:
- Path=/stat/**
- id: model
uri: lb://${model.name}
predicates:
- Path=/model/**
eureka:
client:
service-url:
defaultZone: http://admin:123456@127.0.0.1:8800/eureka/
spring:
cloud:
config:
name: config
profile: @profiles.active@
discovery:
enabled: true
service-id: CONFIG-SERVER
uri: http://127.0.0.1:8300/
eureka:
instance:
prefer-ip-address: true # 使用IP注册服务
lease-renewal-interval-in-seconds: 2 #每间隔1s,向服务端发送一次心跳,证明自己依然"存活"
lease-expiration-duration-in-seconds: 6 #告诉服务端,如果我2s之内没有给你发心跳,就代表我"死"了,将我踢出掉。
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
client:
serviceUrl:
defaultZone: http://admin:123456@127.0.0.1:8800/eureka/
package com.zq;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProducerServerApplicationTestKit {
@Test
public void contextLoads() {
}
}
server:
port: ${gateway.port}
spring:
application:
name: ${gateway.name}
cloud:
gateway:
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Origin, RETAIN_UNIQUE
discovery:
locator:
enabled: true
globalcors:
cors-configurations:
'[/**]':
allowCredentials: true
allowedOrigins: "*"
allowedMethods: "PUT, POST, GET, OPTIONS, DELETE"
allowedHeaders: "Content-type, Authorization"
maxAge: 3600
routes:
- id: api
uri: lb://${api.name}
predicates:
- Path=/api/**
# filters:
#过滤器 设置所有的 方法都会自动添加foo=bar
# - AddRequestParameter=key, bar
#当请求路径匹配到/hello/world/HiController/**会将包含hello和后边的字符串接去掉转发,
#StripPrefix=2就代表截取路径的个数,这样配置后当请求/hello/world/HiController/aaa后端匹配到的请求路径,
#就会变成http://127.0.0.1:8762/HiController/aaa
# - StripPrefix=2
- id: auth
uri: lb://${auth.name}
predicates:
- Path=/auth/**
- id: sys
uri: lb://${sys.name}
predicates:
- Path=/sys/**
- id: instrument
uri: lb://${instrument.name}
predicates:
- Path=/instrument/**
- id: file
uri: lb://${file.name}
predicates:
- Path=/images/**, /file/**
- id: solr
uri: lb://${solr.name}
predicates:
- Path=/solr/**
- id: spider
uri: lb://${spider.name}
predicates:
- Path=/spider/**
- id: docstat
uri: lb://${stat.name}
predicates:
- Path=/docstat/**
- id: stat
uri: lb://${stat.name}
predicates:
- Path=/stat/**
- id: model
uri: lb://${model.name}
predicates:
- Path=/model/**
eureka:
client:
service-url:
defaultZone: http://admin:123456@127.0.0.1:8800/eureka/
spring:
cloud:
config:
name: config
profile: test
discovery:
enabled: true
service-id: CONFIG-SERVER
uri: http://127.0.0.1:8300/
eureka:
instance:
prefer-ip-address: true # 使用IP注册服务
lease-renewal-interval-in-seconds: 2 #每间隔1s,向服务端发送一次心跳,证明自己依然"存活"
lease-expiration-duration-in-seconds: 6 #告诉服务端,如果我2s之内没有给你发心跳,就代表我"死"了,将我踢出掉。
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
client:
serviceUrl:
defaultZone: http://admin:123456@127.0.0.1:8800/eureka/
version=1.0.0
groupId=com.zq
artifactId=gateway-server
D:\Java Project\nnjcy-data-model\gateway-server\src\main\java\com\zq\gateway\GatewayApplication.java
D:\Java Project\nnjcy-data-model\gateway-server\src\test\java\com\zq\ProducerServerApplicationTestKit.java
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.zq</groupId>
<artifactId>nnjcy-data-model</artifactId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>model-server</artifactId>
<dependencies>
<dependency>
<groupId>com.zq</groupId>
<artifactId>common-client</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--Spring boot 安全框架-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 连接配置中心 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--Spring boot Web容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Spring boot 测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Spring boot Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--Mybatis plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis.plus.version}</version>
</dependency>
<!-- druid数据源驱动 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<!-- apache poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!--pdfbox依赖-->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>22.3</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-words-22.8.0-jdk17.jar</systemPath>
</dependency>
<dependency>
<groupId>com.zq</groupId>
<artifactId>sys-server</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.zq</groupId>
<artifactId>instrument-server</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- 让maven不编译docx文件,但仍将其打包 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>docx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<!--开启过滤,用指定的参数替换directory下的文件中的参数-->
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
package com.zq.model;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.zq.model.mapper")
public class ModelApplication {
public static void main(String[] args) {
SpringApplication.run(ModelApplication.class, args);
}
}
\ No newline at end of file
package com.zq.model.config;/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.zq.common.base.SecurityProperties;
import com.zq.common.config.redis.RedisUtils;
import com.zq.common.vo.AppTokenVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* @author /
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class AppTokenUtils implements InitializingBean {
private RedisUtils redisUtils;
private static final String APP_TOKEN_KEY = "appToken";
private static Key key;
private static SignatureAlgorithm signatureAlgorithm;
@Override
public void afterPropertiesSet() {
signatureAlgorithm = SignatureAlgorithm.HS512;
byte[] keyBytes = DatatypeConverter.parseBase64Binary(SecurityProperties.BASE64SECRET);
key = new SecretKeySpec(keyBytes, signatureAlgorithm.getJcaName());
}
public static String createToken(AppTokenVo tokenVo, long minutes) {
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
JwtBuilder jwtBuilder = Jwts.builder()
.setSubject(tokenVo.getPhone())
.setIssuedAt(now)
.claim(APP_TOKEN_KEY, tokenVo)
.signWith(signatureAlgorithm, key)
// 加入ID确保生成的 Token 都不一致
.setId(tokenVo.getUserId().toString());
if (minutes >= 0) {
long expMillis = nowMillis + (minutes * 60 * 1000);
Date exp = new Date(expMillis);
jwtBuilder.setExpiration(exp);
}
return jwtBuilder.compact();
}
public static AppTokenVo getAppTokenVo(String token) {
try {
Claims claims = Jwts.parser()
.setSigningKey(DatatypeConverter.parseBase64Binary(SecurityProperties.BASE64SECRET))
.parseClaimsJws(token)
.getBody();
// fix bug: 当前用户如果没有任何权限时,在输入用户名后,刷新验证码会抛IllegalArgumentException
return JSON.parseObject(JSON.toJSONString(claims.get(APP_TOKEN_KEY)), AppTokenVo.class);
} catch (Exception e) {
return null;
}
}
/**
* @param token 需要检查的token
*/
public void checkRenewal(String token) {
// 判断是否续期token,计算token的过期时间
long time = redisUtils.getExpire(SecurityProperties.ONLINEKEY + token) * 1000;
Date expireDate = DateUtil.offset(new Date(), DateField.MILLISECOND, (int) time);
// 判断当前时间与过期时间的时间差
long differ = expireDate.getTime() - System.currentTimeMillis();
// 如果在续期检查的范围内,则续期
if (differ <= SecurityProperties.DETECT) {
long renew = time + SecurityProperties.RENEW;
redisUtils.expire(SecurityProperties.ONLINEKEY + token, renew, TimeUnit.MILLISECONDS);
}
}
public static String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader(SecurityProperties.HEADER);
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(SecurityProperties.getTokenStartWith())) {
// 去掉令牌前缀
return bearerToken.replace(SecurityProperties.getTokenStartWith(), "");
}
return null;
}
}
package com.zq.model.config;/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Zheng Jie
*/
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
//当用户在没有授权的情况下访问受保护的REST资源时,将调用此方法发送403 Forbidden响应
response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
}
}
package com.zq.model.config;/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Zheng Jie
*/
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
// 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException == null ? "Unauthorized" : authException.getMessage());
}
}
package com.zq.model.config;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author wilmiam
* @since 2021/11/12 11:19
*/
@Component
@ConfigurationProperties(prefix = "project")
public class ProjectConfig {
public static String version = "v1.1";
public static String windowsPath = "D:\\jcy-file";
public static String linuxPath = "/instrument";
public static final String MAPPER_PATH = "/instrument/**";
public static final String HOME_URL = "http://" + NetUtil.getLocalhostStr() + ":9679/";
public static final String SALT = "MaiLu/1301";
public static final String SYSTEM_TAG = "oa-instrument";
public void setVersion(String version) {
ProjectConfig.version = version;
}
public void setWindowsPath(String windowsPath) {
ProjectConfig.windowsPath = windowsPath;
if (FileUtil.exist(windowsPath)) {
FileUtil.mkdir(windowsPath);
}
}
public void setLinuxPath(String linuxPath) {
ProjectConfig.linuxPath = linuxPath;
if (FileUtil.exist(linuxPath)) {
FileUtil.mkdir(linuxPath);
}
}
/**
* 获取当前系统路径
*
* @return
*/
public static String getSysPath() {
OsInfo osInfo = SystemUtil.getOsInfo();
if (osInfo.isWindows()) {
return windowsPath;
} else if (osInfo.isLinux()) {
return linuxPath;
}
return linuxPath;
}
}
package com.zq.model.config;
import com.zq.common.annotation.AnonymousAccess;
import com.zq.common.config.redis.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.core.GrantedAuthorityDefaults;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author Zheng Jie
*/
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final TokenProvider tokenProvider;
private RedisUtils redisUtils;
private final JwtAuthenticationEntryPoint authenticationErrorHandler;
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
private final ApplicationContext applicationContext;
@Bean
public GrantedAuthorityDefaults grantedAuthorityDefaults() {
// 去除 ROLE_ 前缀
return new GrantedAuthorityDefaults("");
}
@Bean
public PasswordEncoder passwordEncoder() {
// 密码加密方式
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// 搜寻匿名标记 url: @AnonymousAccess
Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods();
Set<String> anonymousUrls = new HashSet<>();
anonymousUrls.add("/model/**/**");
for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethodMap.entrySet()) {
HandlerMethod handlerMethod = infoEntry.getValue();
AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class);
if (null != anonymousAccess) {
anonymousUrls.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
}
}
httpSecurity
// 禁用 CSRF
.csrf().disable()
// .addFilterBefore(new CorsConfig(), UsernamePasswordAuthenticationFilter.class) //在指定过滤器前添加过滤器
// 授权异常
.exceptionHandling()
.authenticationEntryPoint(authenticationErrorHandler)
.accessDeniedHandler(jwtAccessDeniedHandler)
// 防止iframe 造成跨域
.and()
.headers()
.frameOptions()
.disable()
// 不创建会话
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
// 静态资源等等
.antMatchers(
HttpMethod.GET,
"/*.html",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/**/*.xlxs",
"/webSocket/**"
).permitAll()
// swagger 文档
.antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/*/api-docs").permitAll()
// 文件
.antMatchers("/avatar/**").permitAll()
.antMatchers("/file/**").permitAll()
// 阿里巴巴 druid
.antMatchers("/druid/**").permitAll()
.antMatchers("/test/**").permitAll()
// 放行OPTIONS请求
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// 自定义匿名访问所有url放行 : 允许匿名和带权限以及登录用户访问
.antMatchers(anonymousUrls.toArray(new String[0])).permitAll()
.antMatchers("/instrument/notSueCaseReview/getUnReviewNotSueCase/**").authenticated()
.antMatchers("/instrument/notSueCaseReview/getReviewNotSueCaseHistory/**").authenticated()
.antMatchers("/instrument/handling/getNotSueCase/**").authenticated()
// 所有请求都需要认证
.anyRequest().authenticated()
.and().apply(securityConfigurerAdapter());
}
private TokenConfigurer securityConfigurerAdapter() {
return new TokenConfigurer(tokenProvider);
}
}
package com.zq.model.config;/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.zq.common.config.redis.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
* @author /
*/
@RequiredArgsConstructor
public class TokenConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
private final TokenProvider tokenProvider;
private RedisUtils redisUtils;
@Override
public void configure(HttpSecurity http) {
TokenFilter customFilter = new TokenFilter(tokenProvider, redisUtils);
http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
}
}
package com.zq.model.config;/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import cn.hutool.core.util.StrUtil;
import com.zq.common.base.SecurityProperties;
import com.zq.common.config.redis.RedisUtils;
import com.zq.common.utils.TokenUtils;
import com.zq.common.vo.OnlineUserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* @author /
*/
@Slf4j
public class
TokenFilter extends GenericFilterBean {
private final TokenProvider tokenProvider;
private RedisUtils redisUtils;
public TokenFilter(TokenProvider tokenProvider, RedisUtils redisUtils) {
this.tokenProvider = tokenProvider;
this.redisUtils = redisUtils;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String token = TokenProvider.resolveToken(httpServletRequest);
// 对于 Token 为空的不需要去查 Redis
if (StrUtil.isNotBlank(token)) {
OnlineUserDto onlineUserDto = null;
try {
onlineUserDto = redisUtils.getObj(SecurityProperties.ONLINEKEY + token, OnlineUserDto.class);
} catch (Exception e) {
log.error(e.getMessage());
}
if (onlineUserDto != null && StringUtils.hasText(token)) {
Authentication authentication = tokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
// Token 续期
tokenProvider.checkRenewal(token);
// 存到线程上下文
TokenUtils.setAdminContext(onlineUserDto);
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
}
package com.zq.model.config;/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zq.common.base.SecurityProperties;
import com.zq.common.config.redis.RedisUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* @author /
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class TokenProvider implements InitializingBean {
private RedisUtils redisUtils;
private static final String AUTHORITIES_KEY = "auth";
private static Key key;
private static SignatureAlgorithm signatureAlgorithm;
@Override
public void afterPropertiesSet() {
signatureAlgorithm = SignatureAlgorithm.HS512;
byte[] keyBytes = DatatypeConverter.parseBase64Binary(SecurityProperties.BASE64SECRET);
key = new SecretKeySpec(keyBytes, signatureAlgorithm.getJcaName());
}
public static String createToken(Authentication authentication) {
String authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));
return Jwts.builder()
.setSubject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.signWith(signatureAlgorithm, key)
// 加入ID确保生成的 Token 都不一致
.setId(IdUtil.simpleUUID())
.compact();
}
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(DatatypeConverter.parseBase64Binary(SecurityProperties.BASE64SECRET))
.parseClaimsJws(token)
.getBody();
// fix bug: 当前用户如果没有任何权限时,在输入用户名后,刷新验证码会抛IllegalArgumentException
Object authoritiesStr = claims.get(AUTHORITIES_KEY);
Collection<? extends GrantedAuthority> authorities =
ObjectUtil.isNotEmpty(authoritiesStr) ?
Arrays.stream(authoritiesStr.toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList()) : Collections.emptyList();
User principal = new User(claims.getSubject(), "", authorities);
return new UsernamePasswordAuthenticationToken(principal, token, authorities);
}
/**
* @param token 需要检查的token
*/
public void checkRenewal(String token) {
// 判断是否续期token,计算token的过期时间
long time = redisUtils.getExpire(SecurityProperties.ONLINEKEY + token) * 1000;
Date expireDate = DateUtil.offset(new Date(), DateField.MILLISECOND, (int) time);
// 判断当前时间与过期时间的时间差
long differ = expireDate.getTime() - System.currentTimeMillis();
// 如果在续期检查的范围内,则续期
if (differ <= SecurityProperties.DETECT) {
long renew = time + SecurityProperties.RENEW;
redisUtils.expire(SecurityProperties.ONLINEKEY + token, renew, TimeUnit.MILLISECONDS);
}
}
public static String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader(SecurityProperties.HEADER);
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(SecurityProperties.getTokenStartWith())) {
// 去掉令牌前缀
return bearerToken.replace(SecurityProperties.getTokenStartWith(), "");
}
return null;
}
}
package com.zq.model.constant;
/**
* @program: instrument-cloud
* @description:
* @author: xiaoliang
* @create: 2023-06-21 16:37
*/
public interface RegexConstants {
/** 根据系统选择全局换行符 */
// String SYMBOL = MyUtils.isWindows() ? "\r\n" : "\n";
/** 某些情况下可能是\r\n */
String SYMBOL = "\n";
/** 起诉意见书正则 */
String QISUSHU_REGEX = "(?<=局"+SYMBOL+"起诉意见书"+SYMBOL+")([\\s\\S]*?)(?=此致)";
/** 起诉意见书文书号正则 */
String DOC_NO_INDICTMENT_REGEX = "南公(.*?)号";
/** 判决书案号正则 */
String JUDGMENT_CASE_NO = "(.*?)号";
/** 嫌疑人姓名正则 */
String PERSON_NAME_REGEX = "(?<=号犯罪嫌疑人)([\\s\\S]*?)(?=,)";
String PERSON_NAME_REGEX1 = "(?<=号犯罪嫌疑人基本情况)([\\s\\S]*?)(?=,)";
/** 嫌疑人户籍正则 */
String PERMANENT_ADDRESS_REGEX = "(?<=户籍所在地|户籍地址|户籍住址|户籍地)([\\s\\S]*?)(?=,)";
/** 嫌疑人现住址正则 */
// String HOUSE_ADDRESS_REGEX = "(?<=现住址|住址|现住)([\\s\\S]*?)(?=,)";
String HOUSE_ADDRESS_REGEX = "(?<=现住址|住址:|现住|住:)([\\s\\S]*?)(?=。|,)";
/** 嫌疑人身份证号正则 */
String PERSON_ID_CARD_REGEX = "(?<=居民身份证号码|身份证号码|居民身份证:)([\\s\\S]*?)(?=,)";
/** 嫌疑人民族正则 */
// String NATION_REGEX = "(?<=,)([\\u4e00-\\u9fa5]*族)(?=,)";
String NATION_REGEX = "(?:汉族|蒙古族|回族|藏族|维吾尔族|苗族|彝族|壮族|布依族|朝鲜族|满族|侗族|瑶族|白族|土家族|哈尼族|哈萨克族|傣族|黎族|傈僳族|佤族|畲族|高山族|拉祜族|水族|东乡族|纳西族|景颇族|柯尔克孜族|土族|达斡尔族|仫佬族|羌族|布朗族|撒拉族|毛南族|仡佬族|锡伯族|阿昌族|普米族|塔吉克族|怒族|乌孜别克族|俄罗斯族|鄂温克族|德昂族|保安族|裕固族|京族|塔塔尔族|独龙族|鄂伦春族|赫哲族|门巴族|珞巴族)";
/** 侦查查明事实正则 */
// String INVESTIGATION_REGEX = "(?<=经依法侦查查明|经审讯和调查)([\\s\\S]*?)(?=认定上述犯罪事实的证据如下|认定上述事实的证据如下|认罪认罚情况)";
String INVESTIGATION_REGEX = "(?<=经依法侦查查明|经审讯和调查)([\\s\\S]*?)(?<=涉嫌危险驾驶犯罪。|涉嫌危险驾驶。|涉嫌危险驾驶罪。|已达到醉酒驾驶机动车标准。)";
/** 血液酒精浓度正则 */
String ETHANOL_CONCENTRATION_REGEX = "(?<=静脉血液乙醇浓度为|浓度为)([\\s\\S]*?)(?=mg/)";
/** 呼气酒精浓度正则 */
String ALCOHOL_CONTENT_REGEX = "(?=气体|呼吸|呼气|吹气|呼出.?气体)[\\u4e00-\\u9fa5\\s\\,\\:]*(\\d*.\\d*)[^\\d]*(?=mg\\/)";
/** 到案经过正则 */
String CATCH_DESC_REGEX = "(?<=到案经过"+SYMBOL+")([\\s\\S]*?)(?<=。" + SYMBOL+")";
/** 抽检医院正则 */
String APPRAISAL_HOSPITAL_REGEX = "(?<=地点:)([\\s\\S]*?)(?<=医院)";
/** 准驾车型正则 */
String DRIVING_LICENSE_TYPE_REGEX1 = "(?<=准驾车型:)([\\s\\S]*?)(?=" + SYMBOL + ")";
String DRIVING_LICENSE_TYPE_REGEX2 = "(?<=准驾车型:)([\\s\\S]*?)(?=,|" + SYMBOL + ")";
/** 讯问笔录中个人情况正则 */
String PERSON_INFO_REGEX = "(?<=你的个人(.{0,2})情况|你的个人情况)([\\s\\S]*?)(?=问:)";
/** 职业类型正则 */
String WORK_TYPE_REGEX = "(?<=职业:)([\\s\\S]*?)(?=,|。)";
/** 讯问笔录中辩解正则 */
String DECLARATION_REGEX = "(?<=问:你把当时的情况详细地说一遍" +
"|请你把事故经过说一下" +
"|说一下当晚的情况" +
"|你把当天的事情经过详细的叙述一遍" +
"|请你如实陈述被查获当天事情的经过" +
"|请你如实陈述事情的经过" +
"|你详细说一下事情经过" +
"|请你将上述的事情经过如是讲述,情况如何" +
"|请你讲一讲当天的经过" +
"|说一下当天事发经过)" +
"([\\s\\S]*?)(?<=问:)";
/** 询问笔录口供 */
String RECORD_OF_INQUIRY_REGEX = "(?<=问:你把事故发生的经过讲一遍)([\\s\\S]*?)(?<=问:)";
/** 询问笔录个人情况 */
String GRQK_REGEX = "(?<=你的个人基本情况|你的个人情况)([\\s\\S]*?)(?<=问:)";
/** 辩解内容正则 */
String DECLARATION_REGEX1 = "(?<=答:)([\\s\\S]*?)(?=问:)";
/** 去除页码正则 */
String REPLACE_PAGINATION_REGEX = "第(.*)页(.*)共(.*)页|第(.*)页|共(.*)页";
/** 乙醇鉴定文书号正则,解释:"从司法鉴定意见书\n"开始,中间是否包含"毒",到"号"结束 */
String DOC_NO_APPRAISAL_REGEX = "(?<=司法鉴定意见书"+ SYMBOL +")(?=.*毒)([\\s\\S]*?)(?<=号)";
// String DOC_NO_APPRAISAL_REGEX = "(?<=司法鉴定意见书"+ SYMBOL +")(?=.*毒|.*司)([\\s\\S]*?)(?<=\\S\\d号)";
// String DOC_NO_APPRAISAL_REGEX = "(?<=司法鉴定意见书"+ SYMBOL +")(?=.*毒|)([\\s\\S]*?)(?<=\\S\\d号)";
/** 车牌号正则 */
String CAR_LICENSE_REGEX1 = "(?<=机动车号牌号码:)([\\s\\S]{7})";
String CAR_LICENSE_REGEX2 = "[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}";
/** 字符串中提取日期正则 */
String DATE_REGEX = "(\\d{4}年\\d{1,2}月\\d{1,2}日)";
/** 机动车类型 */
String MOTOR_VEHICLES_TYPE = "(?<=机动车类型:)([\\s\\S]*?)(?="+SYMBOL+")";
/** 身份证正则 */
String ID_CARD_REGEX = "[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]";
// 文化程度
String EDUCATION_LEVEL_REGEX = "(?<=文化程度)([\\s\\S]*?)(?=,)";
// String DATE_REGEX = "(\\d{4}年\\d{1,2}.\\d{1,2}日(\\d{1,2}时)?)";
/**************************/
/** 酒精 */
String ETHANOL_REGEX = "[\\u4e00-\\u9fa5\\s]*(\\d*.\\d*)[^\\d]*(?=mg\\/)";
/** 只取数字 */
String NUMBER_REGEX = "[0-9]+([.]{1}[0-9]+){0,1}";
/** 截取罪名 */
String ACCUSATION_REGEX = "(?<=犯)[\\u4e00-\\u9fa5]{2,}(?<=罪)";
/** 找到判决书是何种判决书 例如:民事判决书、刑事判决书等 */
String VERDICT = "(?<=人民法院)([\\s\\S]*?)(?<=判决书|裁定书|决定书)";
/**************************/
/**欠款金额*/
String ARREARS_MONEY_REGEX="(?<=共计人民币|共计|共借款)(\\d+)(?=万元|元)";
/**被告姓名*/
String DEFENDANT_NAME_REGEX= "(?<=被告|被告:)([\\s\\S]*?)(?=、|,)";
/**原告姓名*/
String PLAINTIFF_NAME_REGEX= "(?<=原告|原告:)([\\s\\S]*?)(?=、|,)";
/**被告参与诉讼情况 */
String JOIN_PROCEEDING_REGEX= "(?<=,被告)([\\s\\S]*?)(?<=参加诉讼|缺席审理)";
/**判决内容*/
String JUDGMENT_CONTENT_REGEX= "(?<=判决如下:\\n)([\\s\\S]*?)(?<=元\\.|元。)";
}
\ No newline at end of file
package com.zq.model.controller;
import com.zq.common.annotation.AnonymousAccess;
import com.zq.common.vo.ResultVo;
import com.zq.model.service.impl.BjService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
/**
* @author zheng qing
* @date 2023/6/8
*/
@RestController
@RequestMapping("/model/bj")
public class BjController {
@Resource
private BjService bjService;
@PostMapping("/importDb")
@AnonymousAccess
public ResultVo<Boolean> importDb(MultipartFile file) throws Exception{
return ResultVo.success(bjService.importToDb(file.getInputStream()));
}
@PostMapping("/importDishonesty")
@AnonymousAccess
public ResultVo importDishonesty(MultipartFile file) throws Exception{
return ResultVo.success(bjService.importDishonesty(file));
}
}
package com.zq.model.controller;
import com.zq.common.annotation.AnonymousAccess;
import com.zq.common.utils.AssertUtils;
import com.zq.common.vo.ResultVo;
import com.zq.model.entity.LoanJudgmentCase;
import com.zq.model.service.JudgmentService;
import com.zq.model.vo.LoanCaseInfoVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
/**
* @program: instrument-cloud
* @description:
* @author:
* @create:
*/
@RestController
@RequestMapping("/model/judgment")
class JudgMentController {
@Resource
private JudgmentService judgmentService;
@AnonymousAccess
@ApiOperation("导入判决书案件")
@PostMapping("/uploadCase")
public ResultVo uploadJudgCase(@RequestParam("file") MultipartFile[] multipartFiles){
AssertUtils.notNull(multipartFiles, "文件不能为空!");
try {
return ResultVo.success(judgmentService.upload(multipartFiles));
} catch (Exception e) {
e.printStackTrace();
return ResultVo.fail(500, "文件解析失败");
}
}
// @AnonymousAccess
// @ApiOperation("判决书案件列表")
// @PostMapping("/caseList")
// public ResultVo caseList(@RequestParam("file") MultipartFile[] files){
// AssertUtils.notNull(files, "文件不能为空!");
// try {
// return ResultVo.success(judgmentService.uploadList(files));
// } catch (Exception e) {
// e.printStackTrace();
// return ResultVo.fail(500, "文件解析失败");
// }
// }
@AnonymousAccess
@ApiOperation("查询相同原告")
@PostMapping("/selectCountCase")
public ResultVo selectCountCase(@RequestBody LoanJudgmentCase vo){
return ResultVo.success(judgmentService.selectCountCase()) ;
}
}
package com.zq.model.controller;
import com.zq.common.annotation.AnonymousAccess;
import com.zq.common.vo.ResultVo;
import com.zq.model.service.LawjService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @program: instrument-cloud
* @description: 隆安未检数据模型
* @author: xiaoliang
* @create: 2023-05-19 09:31
*/
@RestController
@RequestMapping("/model/lawj")
public class LawjController {
@Resource
private LawjService lawjService;
@AnonymousAccess
@ApiOperation("获取流程")
@GetMapping("/flow")
public ResultVo getFlow(){
return ResultVo.success(lawjService.getFlow());
}
@AnonymousAccess
@ApiOperation("数据碰撞")
@GetMapping("/collision/{tableId}")
public ResultVo collision(@PathVariable("tableId") Integer tableId){
return ResultVo.success(lawjService.collision(tableId));
}
@AnonymousAccess
@ApiOperation("获取字段名")
@GetMapping("/field/{tableId}")
public ResultVo getTableField(@PathVariable("tableId") Integer tableId){
return ResultVo.success(lawjService.getTableField(tableId));
}
}
\ No newline at end of file
package com.zq.model.controller;
import com.zq.common.annotation.AnonymousAccess;
import com.zq.common.vo.ResultVo;
import com.zq.model.service.QzylService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
/**
* @program: instrument-cloud
* @description: 强制医疗数据模型
* @author: xiaoliang
* @create: 2023-05-06 15:13
*/
@RestController
@RequestMapping("/model/qzyl")
public class QzylController {
@Resource
private QzylService qzylService;
@AnonymousAccess
@ApiOperation("获取强制医疗案件")
@GetMapping("/case")
public ResultVo getCase(){
return ResultVo.success(qzylService.getCase());
}
@AnonymousAccess
@ApiOperation("更新案件信息")
@PutMapping("/case")
public ResultVo updateCase(@RequestParam String startTime, @RequestParam String endTime){
qzylService.updateCase(startTime, endTime);
return ResultVo.success();
}
@AnonymousAccess
@ApiOperation("数据碰撞")
@PostMapping("/collision")
public ResultVo collision(@RequestBody MultipartFile file){
return ResultVo.success(qzylService.excel(file));
}
@AnonymousAccess
@ApiOperation("导出碰撞后的excel")
@PostMapping("/collision/excel")
public ResultVo excel(@RequestBody MultipartFile file){
return ResultVo.success(qzylService.excel(file));
}
@AnonymousAccess
@ApiOperation("获取字段名")
@GetMapping("/field/{tableId}")
public ResultVo getTableField(@PathVariable("tableId") Integer tableId){
return ResultVo.success(qzylService.getTableField(tableId));
}
}
\ No newline at end of file
package com.zq.model.controller;
import com.zq.common.annotation.AnonymousAccess;
import com.zq.common.vo.ResultVo;
import com.zq.model.service.LoanCaseInfoService;
import com.zq.model.vo.LoanCaseInfoVo;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* @author Hmb
* @since 2023/6/8 20:11
*/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/model/cd")
public class TestController {
private final LoanCaseInfoService loanCaseInfoService;
@AnonymousAccess
@ApiOperation("上传裁定书保存")
@PostMapping("/upload")
public ResultVo updateCase(@RequestParam("file") MultipartFile[] file) {
boolean b = loanCaseInfoService.saveInfo(file);
if (b) {
return ResultVo.success();
} else {
return ResultVo.fail("上传失败");
}
}
@AnonymousAccess
@ApiOperation("查询裁定书裁定书保存")
@PostMapping("/selectCase")
public ResultVo selectBasicCase(@RequestBody LoanCaseInfoVo vo){
return ResultVo.success(loanCaseInfoService.selectBasicCase(vo)) ;
}
}
package com.zq.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "bj_dishonesty_executed")
public class DishonestyExecuted {
/**
* id
*/
@TableId(type = IdType.AUTO)
private Integer id;
/**
*
*/
private Integer sno;
/**
* 案件被告
*/
@ApiModelProperty("案件被告")
private String caseDefendant;
/**
* 强制措施
*/
@ApiModelProperty("强制措施")
private String coerciveMeasures;
/**
* 立案时间
*/
@ApiModelProperty("立案时间")
private String filingTime;
/**
* 执行案号
*/
@ApiModelProperty("执行案号")
private String executeCaseNo;
/**
* 终结
*/
@ApiModelProperty("终结")
private String ending;
/**
* 原告
*/
@ApiModelProperty("原告")
private String plaintiffName;
/**
* 虚假诉讼
*/
@ApiModelProperty("虚假诉讼")
@TableField(value = "sham_proceeding")
private String shamProceeding;
/**
* createTime
*/
private Date createTime;
/**
* updateTime
*/
private Date updateTime;
}
package com.zq.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* @author Hmb
* @since 2023/6/8 20:00
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "m_loan_case_info")
public class LoanCaseInfo {
@TableId(type = IdType.AUTO)
private Integer id;
/**
* 被告
*/
private String defendantName;
private String defendantIdcard;
/**
* 原告
*/
private String plaintiffName;
private String plaintiffIdcard;
/**
* 原案号
*/
private String originalAh;
/**
* 案号
*/
private String ah;
/**
* 案由
*/
private String ay;
private Date createTime;
private Date updateTime;
private String litigationTime;
}
package com.zq.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* @author Hmb
* @since 2023/6/8 20:00
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "loan_case_list")
public class LoanCaseList {
@TableId(type = IdType.AUTO)
private Integer id;
private String caseName;
private String keywords;
private Date createTime;
}
package com.zq.model.entity;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "loan_judgment_case")
public class LoanJudgmentCase {
/**
* 自增id
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 地域
*/
@TableField(value = "area")
@ApiModelProperty(value="地域")
private String area;
/**
* 案件类型(0刑事案件 1民事案件 2行政案件 3赔偿案件 4执行案件)
*/
@TableField(value = "case_type")
@ApiModelProperty(value="案件类型(0刑事案件 1民事案件 2行政案件 3赔偿案件 4执行案件)")
private Integer caseType;
/**
* 罪名
*/
@TableField(value = "charge")
@ApiModelProperty(value="罪名")
private String charge;
/**
* 欠款金额
*/
@TableField(value = "arrears_money")
@ApiModelProperty(value="欠款金额")
private String arrearsMoney;
/**
* 被告人姓名
*/
@TableField(value = "defendant_name")
@ApiModelProperty(value="被告人姓名")
private String defendantName;
/**
* 被告参与诉讼情况
*/
@TableField(value = "join_proceeding")
@ApiModelProperty(value="被告参与诉讼情况")
private String joinProceeding;
/**
* 原告姓名
*/
@TableField(value = "plaintiff_name")
@ApiModelProperty(value="原告姓名")
private String plaintiffName;
/**
* 判决内容
*/
@TableField(value = "judgment_content")
@ApiModelProperty(value="判决内容")
private String judgmentContent;
/**
* 文件路径
*/
@TableField(value = "file_path")
@ApiModelProperty(value="文件路径")
private String filePath;
/**
* 文件名称
*/
@TableField(value = "file_name")
@ApiModelProperty(value="文件名称")
private String fileName;
/**
* 文件内容
*/
@TableField(value = "file_content")
@ApiModelProperty(value="文件内容")
private String fileContent;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
@ApiModelProperty(value="创建时间")
private Date createTime;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
@ApiModelProperty(value="更新时间")
private Date updateTime;
/**
* 案号
*/
@TableField(value = "reference_no")
@ApiModelProperty(value="案号")
private String referenceNo;
/**
* 公告送达
*/
@TableField(value = "notice_arrive")
@ApiModelProperty(value="公告送达")
private String noticeArrive;
}
package com.zq.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "model_qzyl")
public class Qzyl {
@TableId(type = IdType.AUTO)
@ApiModelProperty("id")
private int id;
private String cbbmmc;
private String dqjdbh;
private String cbjcgryxm;
private String cbdwmc;
private String ajzt;
private String ajmc;
private String dqjdmc;
private String ysayaymc;
private String cqyjzt;
private String dqrq;
private String ajlbbm;
private String ysayaydm;
private int blts;
private String bjrq;
private String gdrq;
private String slrq;
private String ysdwdwmc;
private String cbjcgrybm;
private String bmsah;
private String cbbmbm;
private String cbdwbm;
private String ajlbmc;
private String wcrq;
}
\ No newline at end of file
package com.zq.model.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 地域枚举
* @author Hmb
* @since 2022/7/29 10:59
*/
@Getter
@AllArgsConstructor
public enum AreaEnum {
/**地域*/
NANNING("南宁市", "广西壮族自治区南宁市中级人民法院"),
XIXIANGTANG("西乡塘区", "广西壮族自治区南宁市西乡塘区人民法院"),
QINGXIU("青秀区", "广西壮族自治区南宁市青秀区人民法院"),
XINGNING("兴宁区", "广西壮族自治区南宁市兴宁区人民法院"),
LIANGQING("良庆区", "广西壮族自治区南宁市良庆区人民法院"),
JIANGNAN("江南区", "广西壮族自治区南宁市江南区人民法院"),
YONGNING("邕宁区", "广西壮族自治区南宁市邕宁区人民法院"),
WUMING("武鸣区", "广西壮族自治区南宁市武鸣区人民法院"),
LONGAN("隆安县", "广西壮族自治区隆安县人民法院"),
MASHAN("马山县", "广西壮族自治区马山县人民法院"),
HENGZHOU("横州市", "广西壮族自治区横州市人民法院"),
SHANGLIN("上林县", "广西壮族自治区上林县人民法院"),
/**地域*/
CHONGZUO("崇左市", "广西壮族自治区崇左市中级人民法院"),
LONGZHOU("龙州县","广西壮族自治区龙州县人民法院")
;
private final String area;
private final String description;
public static Stream<AreaEnum> stream() {
return Stream.of(AreaEnum.values());
}
public static List<String > getDescriptionList() {
return AreaEnum.stream().map(AreaEnum::getDescription).collect(Collectors.toList());
}
/**
* 根据description获取去area
* @param description
* @return
*/
public static String getCodeByDescription(String description){
for(AreaEnum areaEnum:AreaEnum.values()){
if(description.equals(areaEnum.getDescription())){
return areaEnum.getArea();
}
}
return "";
}
}
package com.zq.model.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 案件类型枚举
* 案件类型(0刑事案件 1民事案件 2行政案件 3赔偿案件 4执行案件) 判决书类型对应案件类型
* @author Hmb
* @since 2022/7/28 17:25
*/
@Getter
@AllArgsConstructor
public enum CaseTypeEnum {
/** 刑事案件 */
CRIMINAL_CASE1(0, "刑事判决书"),
CRIMINAL_CASE2(0, "刑事裁定书"),
CRIMINAL_CASE3(0, "刑事决定书"),
/** 民事案件 */
CIVIL_CASE1(1, "民事判决书"),
CIVIL_CASE2(1, "民事裁定书"),
CIVIL_CASE3(1, "民事决定书"),
/** 行政案件 */
ADMINISTRATIVE_AREA1(2, "行政裁定书"),
ADMINISTRATIVE_AREA2(2, "行政判决书"),
ADMINISTRATIVE_AREA3(2, "行政决定书"),
/** 赔偿案件 */
COMPENSATION_CASES1(3, "赔偿判决书"),
COMPENSATION_CASES2(3, "赔偿裁定书"),
COMPENSATION_CASES3(3, "赔偿决定书"),
/** 执行案件 */
PERFORM_CASE1(4, "执行判决书"),
PERFORM_CASE2(4, "执行裁定书"),
PERFORM_CASE3(4, "执行决定书"),
;
private final Integer code;
private final String description;
public static Stream<CaseTypeEnum> stream() {
return Stream.of(CaseTypeEnum.values());
}
public static List<String > getDescriptionList() {
return CaseTypeEnum.stream().map(CaseTypeEnum::getDescription).collect(Collectors.toList());
}
/**
* 根据description获取code
* @param description
* @return
*/
public static Integer getCodeByDescription(String description){
for(CaseTypeEnum caseTypeEnum:CaseTypeEnum.values()){
if(description.equals(caseTypeEnum.getDescription())){
return caseTypeEnum.getCode();
}
}
return 0;
}
}
package com.zq.model.feignclient;
import com.zq.common.vo.ResultVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE;
/**
* @author Hmb
* @since 2022-07-30 11:31
*/
@FeignClient(name = "file-server",path = "/file")
public interface FileServerFeignClient {
@PostMapping(value = "/uploadSolrFile",consumes = MULTIPART_FORM_DATA_VALUE)
ResultVo<String> uploadSolrFile(@RequestPart("file") MultipartFile file);
}
package com.zq.model.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zq.common.entity.BjCall;
import org.apache.ibatis.annotations.Mapper;
/**
* @author zheng qing
* @date 2023/6/8
*/
@Mapper
public interface BjCallDao extends BaseMapper<BjCall> {
}
package com.zq.model.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zq.common.entity.BjCase;
import org.apache.ibatis.annotations.Mapper;
/**
* @author zheng qing
* @date 2023/6/8
*/
@Mapper
public interface BjCaseDao extends BaseMapper<BjCase> {
}
package com.zq.model.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zq.model.entity.DishonestyExecuted;
import org.springframework.stereotype.Repository;
/**
* (bj_dishonesty_executed)表数据库访问层
*
* @author zq
* @since 2023-06-10 14:20:47
*/
@Repository
public interface BjDishonestyExecutedDao extends BaseMapper<DishonestyExecuted> {
}
package com.zq.model.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zq.model.entity.LoanCaseInfo;
import com.zq.model.vo.LoanCaseInfoVo;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author Hmb
* @since 2023/6/8 21:17
*/
@Repository
public interface LoanCaseInfoMapper extends BaseMapper<LoanCaseInfo> {
List<LoanCaseInfo> selectCaseData(LoanCaseInfoVo vo);
}
package com.zq.model.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zq.model.entity.LoanCaseList;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface LoanCaseListDao extends BaseMapper<LoanCaseList> {
}
package com.zq.model.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zq.common.vo.ResultVo;
import com.zq.model.entity.LoanJudgmentCase;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface LoanJudgmentCaseDao extends BaseMapper<LoanJudgmentCase> {
ResultVo selectCountCase();
}
package com.zq.model.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zq.model.entity.Qzyl;
import org.apache.ibatis.annotations.Mapper;
/**
* @program: instrument-cloud
* @description: 强制医疗数据碰撞
* @author: xiaoliang
* @create: 2023-05-08 09:22
*/
@Mapper
public interface QzylMapper extends BaseMapper<Qzyl> {
}
\ No newline at end of file
package com.zq.model.service;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ZipUtil;
import com.aspose.words.Document;
import com.aspose.words.Paragraph;
import com.aspose.words.Section;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zq.common.vo.ResultVo;
import com.zq.model.enums.AreaEnum;
import com.zq.model.enums.CaseTypeEnum;
import com.zq.model.util.MyUtils;
import com.zq.model.util.POIUtil;
import com.zq.model.constant.RegexConstants;
import com.zq.model.entity.LoanCaseList;
import com.zq.model.entity.LoanJudgmentCase;
import com.zq.model.mapper.LoanCaseListDao;
import com.zq.model.mapper.LoanJudgmentCaseDao;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.*;
@Slf4j
@Service
@RequiredArgsConstructor
@EnableFeignClients(basePackages = {"com.zq.model.feignclient"})
public class JudgmentService {
private final LoanJudgmentCaseService loanJudgmentCaseService;
private final LoanCaseListDao loanCaseListDao;
private final LoanJudgmentCaseDao loanJudgmentCaseDao;
/**
* 案例库上传文件解析并保存到数据库
*
* @param multipartFiles
* @return
*/
public ResultVo upload(MultipartFile[] multipartFiles) throws Exception {
HashMap<String, Object> map = new HashMap<>();
for (MultipartFile multipartFile : multipartFiles) {
String originalFilename = multipartFile.getOriginalFilename();
// 解压路径
String unzipPath = "/data/file/unzip/" + FileUtil.mainName(originalFilename);
File unzip = ZipUtil.unzip(multipartFile.getInputStream(), new File(unzipPath), Charset.forName("GBK"));
File[] fileList = FileUtil.ls(unzip.getAbsolutePath());
for (File file : fileList) {
// 文件或文件夹名(不带后缀)
String filename = FileUtil.mainName(file);
if (file.isDirectory()) {
File[] files = FileUtil.ls(file.getAbsolutePath());
if (ArrayUtil.isEmpty(files)) {
continue;
}
file = files[0];
}
// 所有段落文字
List<String> paragraphs;
try {
paragraphs = getParagraphs(file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
System.out.println("获取[" + file.getAbsoluteFile() + "]段落发生错误");
continue;
}
// System.out.println("[" + filename + "] " + paragraphs);
LoanJudgmentCase build = LoanJudgmentCase.builder().build();
//文件名列表
LoanCaseList caseList = new LoanCaseList();
caseList.setCaseName(filename);
String text=paragraphs+"";
if (text.contains("民间借贷")) {
caseList.setKeywords("1");
} else {
caseList.setKeywords("0");
}
caseList.setCreateTime(DateUtil.date());
loanCaseListDao.insert(caseList);
LambdaQueryWrapper<LoanCaseList> wrapper = Wrappers.lambdaQuery();
List<LoanCaseList> allLists = loanCaseListDao.selectList(wrapper);
LambdaQueryWrapper<LoanCaseList> eq = wrapper.eq(LoanCaseList::getKeywords, "1");
List<LoanCaseList> keywordsLists = loanCaseListDao.selectList(eq);
map.put("allLists", allLists);
map.put("keywordsLists", keywordsLists);
String verdict = MyUtils.subStr(text, RegexConstants.VERDICT);
Integer caseType = (Integer) getValue(CaseTypeEnum.class, verdict);
// 地域
String area = (String) getValue(AreaEnum.class, text);
//判决书案号
String referenceNo = MyUtils.subStr(text, RegexConstants.JUDGMENT_CASE_NO);
if (text.contains("民间借贷")) {
String arrearsMoney = MyUtils.subStr(text, RegexConstants.ARREARS_MONEY_REGEX);
String defendantName = MyUtils.subStr(text, "(?<=被告|被告:)([\\s\\S]*?)(?=,|、)").replaceAll(":|:", "");
String plaintiffName = MyUtils.subStr(text, "(?<=原告:|原告)([\\s\\S]*?)(?=,|、|。)").replaceAll(":|:", "");
String content = MyUtils.subStr(text, RegexConstants.JOIN_PROCEEDING_REGEX);
if (content.contains("未到庭参加诉讼") || content.contains("不到庭参加诉讼")) {
build.setJoinProceeding("未到庭");
} else if (content.contains("缺席审理")) {
build.setJoinProceeding("缺席审理");
}
String judgmentContent = MyUtils.subStr(text, RegexConstants.JUDGMENT_CONTENT_REGEX);
build.setCharge("民间借贷纠纷");
build.setArrearsMoney(arrearsMoney);
build.setDefendantName(defendantName);
build.setPlaintiffName(plaintiffName);
build.setJudgmentContent(judgmentContent);
build.setReferenceNo(referenceNo);
}
build.setArea(area);
build.setFileContent(text);
build.setCaseType(caseType);
build.setFilePath(file.getPath());
build.setFileName(filename);
build.setCreateTime(DateUtil.date());
build.setUpdateTime(DateUtil.date());
loanJudgmentCaseService.save(build);
}
}
return ResultVo.success(map);
}
/**
* 传入枚举类获取枚举值
*
* @param clazz 枚举类对象
* @param text
* @return
* @throws Exception
*/
public static Object getValue(Class<?> clazz, String text) throws Exception {
Method method = clazz.getDeclaredMethod("getDescriptionList");
List result = (List) method.invoke(clazz.getEnumConstants());
for (Object o : result) {
if (text.contains(o.toString())) {
Method m = clazz.getDeclaredMethod("getCodeByDescription", String.class);
return m.invoke(clazz.getEnumConstants(), o.toString());
}
}
return null;
}
/**
* 项目运行后执行一次
* 代码破解
*
* @throws Exception
*/
public static void register() throws Exception {
Class<?> zzjXClass = Class.forName("com.aspose.words.zzXvM");
Constructor<?> constructor = zzjXClass.getDeclaredConstructors()[0];
constructor.setAccessible(true);
Object zzjXInstance = constructor.newInstance();
// zzZ7O
Field zzZ7O = zzjXClass.getDeclaredField("zzhP");
zzZ7O.setAccessible(true);
zzZ7O.set(zzjXInstance, new Date(Long.MAX_VALUE));
// zzBf
Field zzZfB = zzjXClass.getDeclaredField("zzEJ");
zzZfB.setAccessible(true);
Class<?> zzYP3Class = Class.forName("com.aspose.words.zzXui");
Field zzBfField = zzYP3Class.getDeclaredField("zzXed");
zzBfField.setAccessible(true);
zzZfB.set(zzjXInstance, zzBfField.get(null));
// zzZjA
Field zzZjA = zzjXClass.getDeclaredField("zzKy");
zzZjA.setAccessible(true);
zzZjA.set(null, zzjXInstance);
Class<?> zzCnClass = Class.forName("com.aspose.words.zzVOo");
Field zzZyx = zzCnClass.getDeclaredField("zzZtE");
zzZyx.setAccessible(true);
zzZyx.set(null, 128);
Field zzZ8w = zzCnClass.getDeclaredField("zzZ3p");
zzZ8w.setAccessible(true);
zzZ8w.set(null, false);
}
public static List<String> getParagraphs(String filePath) throws Exception {
Document document = new Document(filePath);
List<String> paragraphs = new ArrayList<>();
for (Section section : document.getSections()) {
for (Paragraph paragraph : section.getBody().getParagraphs()) {
String text = paragraph.getText().trim();
paragraphs.add(text);
}
}
return paragraphs;
}
public ResultVo selectCountCase() {
return ResultVo.success(loanJudgmentCaseDao.selectCountCase());
}
}
package com.zq.model.service;
import java.util.List;
/**
* @program: instrument-cloud
* @description: 隆安未检数据模型
* @author: xiaoliang
* @create: 2023-05-19 09:39
*/
public interface LawjService {
String getFlow();
String collision(Integer tableId);
List<List<String>> getTableField(Integer tableId);
}
\ No newline at end of file
package com.zq.model.service;
import com.zq.common.vo.ResultVo;
import com.zq.model.vo.LoanCaseInfoVo;
import org.springframework.web.multipart.MultipartFile;
/**
* @author Hmb
* @since 2023/6/8 21:20
*/
public interface LoanCaseInfoService {
boolean saveInfo(MultipartFile[] file);
ResultVo selectBasicCase(LoanCaseInfoVo vo);
}
package com.zq.model.service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zq.model.entity.LoanJudgmentCase;
import com.zq.model.mapper.LoanJudgmentCaseDao;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
/**
* @author Hmb
* @since 2022-07-30 12:07
*/
@Service
@RequiredArgsConstructor
public class LoanJudgmentCaseService extends ServiceImpl<LoanJudgmentCaseDao, LoanJudgmentCase> {
}
\ No newline at end of file
package com.zq.model.service;
import com.zq.model.entity.Qzyl;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
/**
* @program: instrument-cloud
* @description: 强制医疗数据模型
* @author: xiaoliang
* @create: 2023-05-06 15:15
*/
public interface QzylService {
List<Qzyl> getCase();
void updateCase(String startTime, String endTime);
List<String> collision(MultipartFile file);
Map excel(MultipartFile file);
List<List<String>> getTableField(Integer tableId);
}
\ No newline at end of file
package com.zq.model.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zq.common.entity.BjCall;
import com.zq.common.entity.BjCase;
import com.zq.common.exception.BusinessException;
import com.zq.common.vo.ResultVo;
import com.zq.model.entity.DishonestyExecuted;
import com.zq.model.mapper.BjCallDao;
import com.zq.model.mapper.BjCaseDao;
import com.zq.model.mapper.BjDishonestyExecutedDao;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
/**
* @author zheng qing
* @date 2023/6/8
*/
@Service
public class BjService {
@Resource
private BjCallDao bjCallDao;
@Resource
private BjCaseDao bjCaseDao;
@Resource
private BjDishonestyExecutedDao bjDishonestyExecutedDao;
public boolean importToDb(InputStream xlsInputStream) throws Exception{
Workbook workbook;
byte[] bytes = IOUtils.toByteArray(xlsInputStream);
InputStream workbookInputStream = new ByteArrayInputStream(bytes);
try {
//2007之后的版本 xlsx
workbook = new XSSFWorkbook(workbookInputStream);
}catch (Exception e){
//2003之前的版本 xls
workbookInputStream =new ByteArrayInputStream(bytes);
workbook = new HSSFWorkbook(workbookInputStream);
}
boolean isCall = true;
List<BjCall> bjCallDaoList = new LinkedList<>();
List<BjCase> bjCaseDaoList = new LinkedList<>();
Sheet sheet = workbook.getSheetAt(0);
for (int i = 2;i<=sheet.getLastRowNum();i++){
Row row = sheet.getRow(i);
// System.out.println(cellToString(row.getCell(0)));
if (cellToString(row.getCell(0)).contains("当事人")){
isCall = false;
continue;
}
if (isCall) {
BjCall bjCall = BjCall.builder()
.person(cellToString(row.getCell(0)))
.callTime(cellToString(row.getCell(1)))
.content(cellToString(row.getCell(2)))
.involvePerson(cellToString(row.getCell(3)))
.note(cellToString(row.getCell(4)))
.build();
if (bjCall.getPerson().trim().equals(""))continue;
bjCallDaoList.add(bjCall);
}else {
BjCase bjCase = BjCase.builder()
.person(cellToString(row.getCell(0)))
.callTime(cellToString(row.getCell(1)))
.content(cellToString(row.getCell(2)))
.involvePerson(cellToString(row.getCell(3)))
.note(cellToString(row.getCell(4)))
.build();
if (bjCase.getPerson().trim().equals(""))continue;
bjCaseDaoList.add(bjCase);
}
}
for (BjCall bjCall:bjCallDaoList){
bjCallDao.insert(bjCall);
}
for (BjCase bjCase:bjCaseDaoList){
bjCaseDao.insert(bjCase);
}
return true;
}
public String cellToString(Cell cell){
if (cell==null){
return "";
}
return cell.getStringCellValue();
}
@Transactional(rollbackFor = Exception.class)
public Object importDishonesty(MultipartFile file) {
ExcelReader reader;
try {
reader = ExcelUtil.getReader(file.getInputStream());
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException("文件解析失败");
}
List<List<Object>> readList = reader.read(2);
DishonestyExecuted executed = new DishonestyExecuted();
for (List<Object> objectList : readList) {
int index = 0;
executed.setSno(Convert.toInt(CollUtil.get(objectList, 0)));
executed.setCaseDefendant(Convert.toStr(CollUtil.get(objectList, 1)));
executed.setCoerciveMeasures(Convert.toStr(CollUtil.get(objectList, 2)));
executed.setFilingTime(Convert.toStr(CollUtil.get(objectList, 3)));
executed.setExecuteCaseNo(Convert.toStr(CollUtil.get(objectList, 4)));
executed.setEnding(Convert.toStr(CollUtil.get(objectList, 5)));
executed.setPlaintiffName(Convert.toStr(CollUtil.get(objectList, 6)));
executed.setShamProceeding(Convert.toStr(CollUtil.get(objectList, 7)));
executed.setCreateTime(DateUtil.date());
executed.setUpdateTime(DateUtil.date());
bjDishonestyExecutedDao.insert(executed);
}
List<DishonestyExecuted> selectList = bjDishonestyExecutedDao.selectList(Wrappers.lambdaQuery(DishonestyExecuted.builder().build()));
return ResultVo.success(selectList);
}
}
package com.zq.model.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zq.common.vo.ResultVo;
import com.zq.model.constant.RegexConstants;
import com.zq.model.entity.LoanCaseInfo;
import com.zq.model.mapper.LoanCaseInfoMapper;
import com.zq.model.service.LoanCaseInfoService;
import com.zq.model.util.MyUtil;
import com.zq.model.util.UnZipUtil;
import com.zq.model.vo.LoanCaseInfoVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author Hmb
* @since 2023/6/8 21:20
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class LoanCaseInfoServiceImpl extends ServiceImpl<LoanCaseInfoMapper, LoanCaseInfo> implements LoanCaseInfoService {
private final LoanCaseInfoMapper loanCaseInfoMapper;
@Override
public boolean saveInfo(MultipartFile[] multipartFiles) {
String dirPath = "/data/tmp/fileta/";
try {
for (MultipartFile multipartFile : multipartFiles) {
File file = MyUtil.multipartFileToFile(multipartFile);
UnZipUtil.unzipWithStream(Files.newInputStream(file.toPath()), dirPath);
List<File> fileList = MyUtil.getAllFilesInDirectory(dirPath);
for (File f : fileList) {
String content = MyUtil.getContent(f);
content = content.replaceAll("\t", "").replaceAll(" ", "");
String plaintiffName = MyUtil.subStr(content, "(?<=原审原告:)([\\s\\S]*?)(?=,|、)").replaceAll(":|:", "");
log.info("原审原告:{}", plaintiffName);
String defendantName = MyUtil.subStr(content, "(?<=原审被告:|被告)([\\s\\S]*?)(?=,|、)").replaceAll(":|:", "");
log.info("原审被告:{}", defendantName);
if (StrUtil.isBlank(defendantName)) {
System.out.println();
}
ArrayList<String> caseNumber = MyUtil.getCaseNumber(content);
if (caseNumber.size() == 0) {
continue;
}
String caseNum = caseNumber.get(0);
String originalCaseNum = caseNumber.get(1);
log.info(caseNumber.toString());
String litigationTime = MyUtil.subStr(content, RegexConstants.DATE_REGEX);
ArrayList<String> idCardList = MyUtil.getIdCard(content);
if (idCardList.size() == 0) {
continue;
}
String plaintiffIdCard = idCardList.get(0);
String defendantIdCard = idCardList.get(1);
log.info(idCardList.toString());
if (defendantIdCard.contains("452133196803280348")) {
defendantIdCard = "452133196803280348";
}
LoanCaseInfo build = LoanCaseInfo.builder()
.ah(caseNum)
.originalAh(originalCaseNum)
.ay("民间借贷纠纷")
.defendantName(defendantName)
.defendantIdcard(defendantIdCard)
.plaintiffName(plaintiffName)
.plaintiffIdcard(plaintiffIdCard)
.litigationTime(litigationTime)
.createTime(new Date())
.updateTime(new Date())
.build();
this.save(build);
}
}
return true;
} catch (Exception e) {
log.error("保存失败:{}", e.getMessage());
return false;
}
}
@Override
public ResultVo selectBasicCase(LoanCaseInfoVo vo) {
return ResultVo.success(loanCaseInfoMapper.selectCaseData(vo));
}
}
package com.zq.model.service.impl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zq.common.exception.BusinessException;
import com.zq.common.utils.AssertUtils;
import com.zq.model.config.ProjectConfig;
import com.zq.model.entity.Qzyl;
import com.zq.model.mapper.QzylMapper;
import com.zq.model.service.QzylService;
import com.zq.model.util.MyExcelUtil;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* @program: instrument-cloud
* @description: 强制医疗数据模型
* @author: xiaoliang
* @create: 2023-05-06 15:15
*/
@Service
public class QzylServiceImpl implements QzylService {
@Resource
private QzylMapper qzylMapper;
@Override
public List<Qzyl> getCase() {
return qzylMapper.selectList(new QueryWrapper<>());
}
@Override
public void updateCase(String startTime, String endTime){
String bodyStr = "{\n" +
" \"ajlbBm\": [\n" +
" \"2017\",\n" +
" \"2018\",\n" +
" \"1743\",\n" +
" \"1744\"\n" +
" ],\n" +
" \"ajmc\": \"\",\n" +
" \"ajzt\": [],\n" +
" \"selectDwbm\": [\n" +
" \"450100\",\n" +
" \"450102\",\n" +
" \"450103\",\n" +
" \"450104\",\n" +
" \"450105\",\n" +
" \"450106\",\n" +
" \"450121\",\n" +
" \"450122\",\n" +
" \"450123\",\n" +
" \"450124\",\n" +
" \"450125\",\n" +
" \"450126\",\n" +
" \"450127\",\n" +
" \"450191\"\n" +
" ],\n" +
" \"dwbm\": \"450100\",\n" +
" \"rybm\": \"4501000102\",\n" +
" \"bmsah\": \"\",\n" +
" \"cbjcg\": \"\",\n" +
" \"cqyj\": [],\n" +
" \"pageNum\": 1,\n" +
" \"pageSize\": 1000,\n" +
" \"sary\": \"\",\n" +
" \"ysayAydm\": [],\n" +
" \"zyhlxdm\": []\n" +
"}";
JSONObject jsonObject = JSONUtil.parseObj(bodyStr);
jsonObject.putOnce("slrqKsrq", startTime);
jsonObject.putOnce("slrqJsrq", endTime);
String respBody = HttpUtil.createPost("http://143.153.78.24:8086/sjdq-service/api/querySubUnitCases")
.header("rwt", "read")
.body(JSONUtil.toJsonStr(jsonObject))
.execute()
.body();
JSONObject body = JSONUtil.parseObj(respBody);
AssertUtils.isTrue(body.getInt("code") == 0, "获取案件信息失败");
List<Qzyl> qzyls = JSONUtil.toList(body.getJSONArray("data"), Qzyl.class);
for (Qzyl qzyl : qzyls) {
Integer row = qzylMapper.selectCount(new LambdaQueryWrapper<Qzyl>().eq(Qzyl::getBmsah, qzyl.getBmsah()));
if(row.intValue() == 0){
qzylMapper.insert(qzyl);
}
}
}
@Override
public List<String> collision(MultipartFile file) {
try {
List<String> values = MyExcelUtil.getSpecifiedColumnValues(file.getInputStream(), 4);
List<String> names = new ArrayList<>(values.size());
for (String value : values) {
Integer row = qzylMapper.selectCount(new LambdaQueryWrapper<Qzyl>().like(Qzyl::getAjmc, value));
if(row.intValue() == 0){
names.add(value);
}
}
return names;
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException("文件读取失败,请检查文件后重试");
}
}
@Override
public Map excel(MultipartFile file) {
List<String> names = collision(file);
try {
String fileUrl = distinctExcel(file.getInputStream(), 4, names, file.getOriginalFilename());
Map map = new HashMap<String, Object>();
map.put("names", names);
map.put("fileUrl", fileUrl);
return map;
} catch (IOException e) {
throw new RuntimeException("文件读取失败,请检查文件后重试");
}
}
@Override
public List<List<String>> getTableField(Integer tableId) {
List<List<String>> list = new ArrayList<>(2);
switch (tableId){
case 1:
list.add(Arrays.asList("承办部门名称", "当前阶段编号", "承办检察官人员姓名", "承办单位名称", "案件状态", "案件名称", "当前阶段名称", "移送案由名称", "审理日期", "报结日期", "移送单位名称", "承办检察官人员编号", "部门受案号", "案件类别名称"));
list.add(Arrays.asList("序号", "鉴定编号", "委托时间", "委托方", "被鉴定人姓名", "案由", "鉴定意见"));
break;
case 2:
list.add(Arrays.asList("过失致人重伤罪", "强奸罪", "绑架罪", "抢夺罪", "聚众斗殴罪", "袭警罪", "寻衅滋事罪", "抢劫罪", "故意杀人罪", "故意伤害罪"));
list.add(Arrays.asList("承办部门名称", "当前阶段编号", "承办检察官人员姓名", "承办单位名称", "案件状态", "案件名称", "当前阶段名称", "移送案由名称", "审理日期", "报结日期", "移送单位名称", "承办检察官人员编号", "部门受案号", "案件类别名称"));
break;
case 3:
list.add(Arrays.asList("案号","案件类别","立案日期","立案案由","当事人名称","原审法院","原审案号","承办审判庭","承办人","结案方式"));
list.add(Arrays.asList("法院名称", "案件类型" ,"案由" ,"涉及金额","被告姓名" ,"未到庭参与诉讼", "缺席审理", "原告姓名", "判决内容", "公告送达" ,"案号"));
case 4:
list.add(Arrays.asList("报警人", "报警时间","涉及的内容","涉及的人"));
list.add(Arrays.asList("追债","还款","高利贷","利息","利滚利","虚假借贷"));
case 5:
list.add(Arrays.asList("案件被告","强制措施","立案时间","执行案号","是否终本","原告","是否序列虚假诉讼"));
list.add(Arrays.asList("案号","案件类别","立案日期","立案案由","当事人名称","原审法院","原审案号","承办审判庭","承办人","结案方式"));
}
return list;
}
public String distinctExcel(InputStream is, int column, List<String> dis, String filename){
XSSFWorkbook workbook = null;
XSSFSheet sheet = null;
try {
workbook = new XSSFWorkbook(is);
int numberOfSheets = workbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
sheet = workbook.getSheetAt(i);
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
for (int j = 1; j <= rowCount; j++) {
String name = (String)MyExcelUtil.getCellValue(sheet.getRow(j).getCell(column));
if(StrUtil.isBlank(name)){
break;
}
if(!dis.contains(name)){
if(rowCount == 1){
sheet.removeRow(sheet.getRow(j));
}else {
sheet.shiftRows(j--+1, rowCount--, -1);
}
}
}
}
String paht = ProjectConfig.getSysPath() + "/model/qzyl" + DateUtil.format(new Date(), "/yyyy/MM/dd") + "/(碰撞)" + filename;
File file = new File(paht);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
FileOutputStream fos = new FileOutputStream(paht);
workbook.write(fos);
return "http://" + NetUtil.getLocalhostStr() + ":9500" + "/file/model/qzyl" + DateUtil.format(new Date(), "/yyyy/MM/dd") + "/(碰撞)" + filename;
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException("文件读取失败,请检查文件后重试");
}finally {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.zq.model.util;
import cn.hutool.core.util.StrUtil;
import com.zq.common.exception.BusinessException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* @program: instrument-cloud
* @description: excel工具类
* @author: xiaoliang
* @create: 2023-05-08 09:39
*/
public class MyExcelUtil {
public static List<String> getSpecifiedColumnValues(InputStream is, int column){
List<String> values = new ArrayList<>();
XSSFWorkbook workbook = null;
XSSFSheet sheet = null;
try {
workbook = new XSSFWorkbook(is);
int numberOfSheets = workbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
sheet = workbook.getSheetAt(i);
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
for (int j = 1; j <= rowCount; j++) {
String name = (String)getCellValue(sheet.getRow(j).getCell(column));
if(StrUtil.isBlank(name)){
break;
}
values.add(name);
}
}
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException("文件读取失败,请检查文件后重试");
}finally {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return values;
}
public static Object getCellValue(Cell cell) {
Object value = null;
DecimalFormat df = new DecimalFormat("0"); // 格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
DecimalFormat df2 = new DecimalFormat("0"); // 格式化数字
switch (cell.getCellType()) {
case STRING:
value = cell.getRichStringCellValue().getString();
break;
case NUMERIC:
if ("General".equals(cell.getCellStyle().getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
value = sdf.format(cell.getDateCellValue());
} else {
value = df2.format(cell.getNumericCellValue());
}
break;
case BOOLEAN:
value = cell.getBooleanCellValue();
break;
case BLANK:
value = "";
break;
default:
break;
}
return value;
}
}
\ No newline at end of file
package com.zq.model.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author zheng qing
* @date 2023/5/8
*/
@Slf4j
public class MyUtil {
/**
* 读取docx文件,转成文本
*/
public static String getContent(InputStream inputStream) throws Exception {
XWPFDocument document = new XWPFDocument(inputStream);
// 读取文档中的段落和文本
// String text =null;
// for (XWPFParagraph paragraph : document.getParagraphs()) {
// System.out.println(paragraph.getText());
// text =paragraph.getText();
//
// }
XWPFWordExtractor extractor = new XWPFWordExtractor(document);
String text = extractor.getText();
extractor.close();
inputStream.close();
document.close();
return text;
}
/**
* 读取docx文件,转成文本
*/
public static String getContent(File file) throws Exception {
return getContent(Files.newInputStream(file.toPath()));
}
/**
* 根据传入的正则截取子串
* @param content 需要从中提取内容的文本
* @param regex 正则表达式
* @return 截取结果
*/
public static String subStr(String content, String regex) {
String result = "";
Pattern patter = Pattern.compile(regex);
Matcher matcher = patter.matcher(content);
while (matcher.find()) {
result = matcher.group();
return result;
}
return result;
}
public static ArrayList<String> getCaseNumber(String text) {
ArrayList<String> list = new ArrayList<>();
// Pattern pattern = Pattern.compile("\\(\\d{4}\\)桂\\d*[\\u4e00-\\u9fff]+\\d+号");
Pattern pattern = Pattern.compile("\\(\\d{4}\\)\\S*[\\u4e00-\\u9fff]+\\d+号");
Matcher m = pattern.matcher(text);
while (m.find()) {
list.add(m.group());
}
return list;
}
public static ArrayList<String> getIdCard(String text) {
ArrayList<String> list = new ArrayList<>();
Pattern pattern = Pattern.compile("[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]");
Matcher m = pattern.matcher(text);
while (m.find()) {
list.add(m.group());
}
return list;
}
/**
* multipartFile转file
*
* @param multipartFile
*/
public static File multipartFileToFile(MultipartFile multipartFile) {
OutputStream out = null;
final File file = new File(multipartFile.getOriginalFilename());
try {
out = Files.newOutputStream(file.toPath());
byte[] ss = multipartFile.getBytes();
for (int i = 0; i < ss.length; i++) {
out.write(ss[i]);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
public static List<File> getAllFilesInDirectory(String dirPath) {
List<File> fileList = new ArrayList<>();
File directory = new File(dirPath);
if (!directory.exists()) {
log.warn("指定的目录不存在!");
return fileList;
}
if (!directory.isDirectory()) {
log.warn("指定的路径不是一个目录!");
return fileList;
}
// 递归获取目录中的所有文件
getAllFiles(directory, fileList);
return fileList;
}
private static void getAllFiles(File directory, List<File> fileList) {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
// 是文件,添加到文件列表
fileList.add(file);
} else if (file.isDirectory()) {
// 是目录,递归调用获取目录下的文件
getAllFiles(file, fileList);
}
}
}
}
}
package com.zq.model.util;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.io.*;
/**
* @author Hmb
* @since 2022/7/29 13:01
*/
public class POIUtil {
/**
* 把一个文件转化为byte字节数组。
*
* @return
*/
public static byte[] fileConvertToByteArray(File file) {
byte[] data = null;
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[1024];
while ((len = fis.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
data = baos.toByteArray();
fis.close();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
// 判断文档类型,调用不同的解析方法
public static String parse(byte[] buffer, String suffix) {
String text = "";
switch (suffix) {
case "doc":
text = getTextFromWord(buffer);
break;
case "docx":
text = getTextFromWord2007(buffer);
break;
case "pdf":
text = getTextFormPDF(buffer);
break;
case "txt":
text = getTextFormTxt(buffer);
break;
default:
System.out.println("不支持解析的文档类型");
}
return text.replaceAll(" ", "");
// return text.replaceAll("\\s*", "");
}
// 读取Word97-2003的全部内容 doc
private static String getTextFromWord(byte[] file) {
String text = "";
InputStream fis = null;
WordExtractor ex = null;
try {
// word 2003: 图片不会被读取
fis = new ByteArrayInputStream(file);
ex = new WordExtractor(fis);
text = ex.getText();
ex.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return text;
}
// 读取Word2007+的全部内容 docx
private static String getTextFromWord2007(byte[] file) {
String text = "";
InputStream fis = null;
XWPFDocument doc = null;
XWPFWordExtractor workbook = null;
try {
fis = new ByteArrayInputStream(file);
doc = new XWPFDocument(fis);
workbook = new XWPFWordExtractor(doc);
text = workbook.getText();
workbook.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return text;
}
// 读取pdf文件全部内容 pdf
private static String getTextFormPDF(byte[] file) {
String text = "";
PDDocument pdfdoc = null;
InputStream is = null;
try {
is = new ByteArrayInputStream(file);
pdfdoc = PDDocument.load(is);
PDFTextStripper stripper = new PDFTextStripper();
text = stripper.getText(pdfdoc);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (pdfdoc != null) {
pdfdoc.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return text;
}
// 读取txt文件全部内容 txt
private static String getTextFormTxt(byte[] file) {
String text = "";
try {
String encoding = get_charset(file);
text = new String(file, encoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return text;
}
// 获得txt文件编码方式
private static String get_charset(byte[] file) throws IOException {
String charset = "GBK";
byte[] first3Bytes = new byte[3];
InputStream bis = null;
try {
boolean checked = false;
bis = new ByteArrayInputStream(file);
bis.mark(0);
int read = bis.read(first3Bytes, 0, 3);
if (read == -1)
return charset;
if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
charset = "UTF-16LE";
checked = true;
} else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {
charset = "UTF-16BE";
checked = true;
} else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB
&& first3Bytes[2] == (byte) 0xBF) {
charset = "UTF-8";
checked = true;
}
bis.reset();
if (!checked) {
while ((read = bis.read()) != -1) {
if (read >= 0xF0)
break;
if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK
break;
if (0xC0 <= read && read <= 0xDF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)
// (0x80 - 0xBF),也可能在GB编码内
continue;
else
break;
} else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小
read = bis.read();
if (0x80 <= read && read <= 0xBF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF) {
charset = "UTF-8";
break;
} else
break;
} else
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
}
}
return charset;
}
}
package com.zq.model.util;
import java.io.*;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnZipUtil {
/**
* 解压zip压缩文件到指定目录
*
* @param zipPath zip压缩文件绝对路径
* @param descDir 指定的解压目录
*/
public static void unzipFile(String zipPath, String descDir) throws IOException {
try {
File zipFile = new File(zipPath);
if (!zipFile.exists()) {
throw new IOException("要解压的压缩文件不存在");
}
File pathFile = new File(descDir);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
InputStream input = new FileInputStream(zipPath);
unzipWithStream(input, descDir);
} catch (Exception e) {
throw new IOException(e);
}
}
/**
* 解压
*
* @param inputStream
* @param descDir
*/
public static void unzipWithStream(InputStream inputStream, String descDir) {
if (!descDir.endsWith(File.separator)) {
descDir = descDir + File.separator;
}
try (ZipInputStream zipInputStream = new ZipInputStream(inputStream,Charset.forName("gbk"))) {
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String zipEntryNameStr = zipEntry.getName();
String zipEntryName = zipEntryNameStr;
if (zipEntryNameStr.contains("/")) {
String str1 = zipEntryNameStr.substring(0, zipEntryNameStr.indexOf("/"));
zipEntryName = zipEntryNameStr.substring(str1.length() + 1);
}
String outPath = (descDir + zipEntryName).replace("\\\\", "/");
File outFile = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!outFile.exists()) {
outFile.mkdirs();
}
if (new File(outPath).isDirectory()) {
continue;
}
writeFile(outPath, zipInputStream);
zipInputStream.closeEntry();
}
System.out.println("======解压成功=======");
} catch (IOException e) {
System.out.println("压缩包处理异常,异常信息{}" + e);
}
}
//将流写到文件中
public static void writeFile(String filePath, ZipInputStream zipInputStream) {
try (OutputStream outputStream = new FileOutputStream(filePath)) {
byte[] bytes = new byte[4096];
int len;
while ((len = zipInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
} catch (IOException ex) {
System.out.println("解压文件时,写出到文件出错");
}
}
//测试方法
public static void main(String[] args) throws IOException {
String zipPath = "C://Users/admin/Desktop/xls.zip";
String descDir = "C://Users/admin/Desktop/outxls";
unzipFile(zipPath, descDir);
}
}
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment