feat: 重构员工控制器并优化JSON序列化配置

refactor(EmployeeController): 重命名EmployyeController为EmployeeController并优化代码结构
feat(EmployeeController): 添加@JsonIgnoreProperties注解解决循环引用问题
feat(JacksonConfig): 新增Jackson配置类处理Hibernate代理和循环引用
fix(EmployeeService): 修复缓存注解格式问题
feat(Employee): 添加@JsonIgnoreProperties注解忽略可能导致循环引用的字段
feat(EmployeeRole): 添加@JsonIgnore注解忽略关联字段
fix(application.properties): 调整Redis缓存配置和错误处理设置
refactor(IndexController): 移除错误处理方法
feat(GlobalExceptionHandler): 新增全局异常处理类
refactor(SecurityConfig): 优化安全配置并启用方法级安全注解
refactor(AbstractCtx): 优化日期时间处理方法
build: 更新项目版本至0.0.53-SNAPSHOT
This commit is contained in:
2025-09-04 16:06:47 +08:00
parent acb63116d5
commit 0e444508ff
21 changed files with 772 additions and 279 deletions

View File

@@ -6,12 +6,12 @@
<parent> <parent>
<groupId>com.ecep.contract</groupId> <groupId>com.ecep.contract</groupId>
<artifactId>Contract-Manager</artifactId> <artifactId>Contract-Manager</artifactId>
<version>0.0.49-SNAPSHOT</version> <version>0.0.53-SNAPSHOT</version>
</parent> </parent>
<groupId>com.ecep.contract</groupId> <groupId>com.ecep.contract</groupId>
<artifactId>client</artifactId> <artifactId>client</artifactId>
<version>0.0.49-SNAPSHOT</version> <version>0.0.53-SNAPSHOT</version>
<properties> <properties>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${java.version}</maven.compiler.source>
@@ -22,7 +22,7 @@
<dependency> <dependency>
<groupId>com.ecep.contract</groupId> <groupId>com.ecep.contract</groupId>
<artifactId>common</artifactId> <artifactId>common</artifactId>
<version>0.0.49-SNAPSHOT</version> <version>0.0.53-SNAPSHOT</version>
</dependency> </dependency>
<!-- JavaFX --> <!-- JavaFX -->
<dependency> <dependency>
@@ -78,6 +78,29 @@
<compress>2</compress> <compress>2</compress>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.16.2</version>
<executions>
<execution>
<inherited>true</inherited>
<id>increment-version</id>
<phase>install</phase>
<goals>
<goal>set</goal>
</goals>
<configuration>
<generateBackupPoms>false</generateBackupPoms>
<processAllModules>true</processAllModules>
<!-- <newVersion>${project.version}</newVersion> -->
<nextSnapshot>true</nextSnapshot>
<nextSnapshotIndexToIncrement>3</nextSnapshotIndexToIncrement>
<!-- <removeSnapshot>true</removeSnapshot>-->
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>

View File

@@ -6,12 +6,12 @@
<parent> <parent>
<groupId>com.ecep.contract</groupId> <groupId>com.ecep.contract</groupId>
<artifactId>Contract-Manager</artifactId> <artifactId>Contract-Manager</artifactId>
<version>0.0.49-SNAPSHOT</version> <version>0.0.53-SNAPSHOT</version>
</parent> </parent>
<groupId>com.ecep.contract</groupId> <groupId>com.ecep.contract</groupId>
<artifactId>common</artifactId> <artifactId>common</artifactId>
<version>0.0.49-SNAPSHOT</version> <version>0.0.53-SNAPSHOT</version>
<properties> <properties>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${java.version}</maven.compiler.source>

View File

@@ -1,15 +1,29 @@
package com.ecep.contract.model; package com.ecep.contract.model;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.proxy.HibernateProxy;
import java.io.Serializable; import java.io.Serializable;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.Objects; import java.util.Objects;
import org.hibernate.proxy.HibernateProxy;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter @Getter
@Setter @Setter
@jakarta.persistence.Entity @jakarta.persistence.Entity
@@ -33,6 +47,7 @@ public class Employee implements BasedEntity, IdentityEntity, NamedEntity, Seria
@JoinColumn(name = "DEPARTMENT_ID") @JoinColumn(name = "DEPARTMENT_ID")
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@ToString.Exclude @ToString.Exclude
@JsonIgnoreProperties({ "leader" })
private Department department; private Department department;
/** /**
@@ -87,6 +102,8 @@ public class Employee implements BasedEntity, IdentityEntity, NamedEntity, Seria
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }) @ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable(name = "EMPLOYEE_ROLES", joinColumns = @JoinColumn(name = "EMPLOYEE_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID")) @JoinTable(name = "EMPLOYEE_ROLES", joinColumns = @JoinColumn(name = "EMPLOYEE_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))
@ToString.Exclude
@JsonIgnore
private java.util.List<EmployeeRole> roles = new java.util.ArrayList<>(); private java.util.List<EmployeeRole> roles = new java.util.ArrayList<>();
@Override @Override

View File

@@ -6,6 +6,8 @@ import lombok.Setter;
import java.io.Serializable; import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Getter @Getter
@Setter @Setter
@jakarta.persistence.Entity @jakarta.persistence.Entity
@@ -43,18 +45,12 @@ public class EmployeeRole implements IdentityEntity, NamedEntity, Serializable {
private boolean active = true; private boolean active = true;
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE }) @ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable( @JoinTable(name = "EMPLOYEE_ROLE_FUNCTIONS", joinColumns = @JoinColumn(name = "ROLE_ID"), inverseJoinColumns = @JoinColumn(name = "FUNC_ID"))
name = "EMPLOYEE_ROLE_FUNCTIONS", @JsonIgnore
joinColumns = @JoinColumn(name = "ROLE_ID"),
inverseJoinColumns = @JoinColumn(name = "FUNC_ID")
)
private java.util.List<Function> functions = new java.util.ArrayList<>(); private java.util.List<Function> functions = new java.util.ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable( @JoinTable(name = "EMPLOYEE_ROLES", joinColumns = @JoinColumn(name = "ROLE_ID"), inverseJoinColumns = @JoinColumn(name = "EMPLOYEE_ID"))
name = "EMPLOYEE_ROLES", @JsonIgnore
joinColumns = @JoinColumn(name = "ROLE_ID"),
inverseJoinColumns = @JoinColumn(name = "EMPLOYEE_ID")
)
private java.util.List<Employee> employees = new java.util.ArrayList<>(); private java.util.List<Employee> employees = new java.util.ArrayList<>();
} }

25
pom.xml
View File

@@ -10,7 +10,7 @@
</parent> </parent>
<groupId>com.ecep.contract</groupId> <groupId>com.ecep.contract</groupId>
<artifactId>Contract-Manager</artifactId> <artifactId>Contract-Manager</artifactId>
<version>0.0.49-SNAPSHOT</version> <version>0.0.53-SNAPSHOT</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<modules> <modules>
<module>server</module> <module>server</module>
@@ -149,29 +149,6 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.16.2</version>
<executions>
<execution>
<inherited>true</inherited>
<id>increment-version</id>
<phase>install</phase>
<goals>
<goal>set</goal>
</goals>
<configuration>
<generateBackupPoms>false</generateBackupPoms>
<processAllModules>true</processAllModules>
<!-- <newVersion>${project.version}</newVersion> -->
<nextSnapshot>true</nextSnapshot>
<nextSnapshotIndexToIncrement>3</nextSnapshotIndexToIncrement>
<!-- <removeSnapshot>true</removeSnapshot>-->
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>

View File

@@ -6,12 +6,12 @@
<parent> <parent>
<groupId>com.ecep.contract</groupId> <groupId>com.ecep.contract</groupId>
<artifactId>Contract-Manager</artifactId> <artifactId>Contract-Manager</artifactId>
<version>0.0.49-SNAPSHOT</version> <version>0.0.53-SNAPSHOT</version>
</parent> </parent>
<groupId>com.ecep.contract</groupId> <groupId>com.ecep.contract</groupId>
<artifactId>server</artifactId> <artifactId>server</artifactId>
<version>0.0.49-SNAPSHOT</version> <version>0.0.53-SNAPSHOT</version>
<properties> <properties>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${java.version}</maven.compiler.source>
@@ -22,7 +22,7 @@
<dependency> <dependency>
<groupId>com.ecep.contract</groupId> <groupId>com.ecep.contract</groupId>
<artifactId>common</artifactId> <artifactId>common</artifactId>
<version>0.0.49-SNAPSHOT</version> <version>0.0.53-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
@@ -69,11 +69,11 @@
<groupId>org.springframework.data</groupId> <groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId> <artifactId>spring-data-jpa</artifactId>
</dependency> </dependency>
<!-- <dependency>--> <!-- <dependency> -->
<!-- <groupId>org.hibernate.orm</groupId>--> <!-- <groupId>org.hibernate.orm</groupId> -->
<!-- <artifactId>hibernate-jpamodelgen</artifactId>--> <!-- <artifactId>hibernate-jpamodelgen</artifactId> -->
<!-- <scope>provided</scope>--> <!-- <scope>provided</scope> -->
<!-- </dependency>--> <!-- </dependency> -->
<dependency> <dependency>
<groupId>com.mysql</groupId> <groupId>com.mysql</groupId>
@@ -89,6 +89,27 @@
<build> <build>
<plugins> <plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.16.2</version>
<executions>
<execution>
<inherited>true</inherited>
<id>increment-version</id>
<phase>install</phase>
<goals>
<goal>set</goal>
</goals>
<configuration>
<generateBackupPoms>false</generateBackupPoms>
<processAllModules>true</processAllModules>
<nextSnapshot>true</nextSnapshot>
<nextSnapshotIndexToIncrement>3</nextSnapshotIndexToIncrement>
</configuration>
</execution>
</executions>
</plugin>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
@@ -103,5 +124,4 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
</project> </project>

View File

@@ -1,10 +1,6 @@
package com.ecep.contract; package com.ecep.contract;
import java.time.Duration; import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale; import java.util.Locale;
import java.util.Properties; import java.util.Properties;
@@ -23,27 +19,20 @@ import org.springframework.boot.context.metrics.buffering.StartupTimeline;
import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySource;
import org.springframework.core.metrics.StartupStep; import org.springframework.core.metrics.StartupStep;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.data.web.config.EnableSpringDataWebSupport.PageSerializationMode;
import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
import com.ecep.contract.cloud.CloudRepositoriesConfig; import com.ecep.contract.cloud.CloudRepositoriesConfig;
import com.ecep.contract.ds.DsRepositoriesConfig; import com.ecep.contract.ds.DsRepositoriesConfig;
import com.ecep.contract.util.TaskMonitorCenter; import com.ecep.contract.util.TaskMonitorCenter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
@SpringBootApplication(exclude = { @SpringBootApplication(exclude = {
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration.class, org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration.class,
@@ -52,6 +41,8 @@ import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
@EnableScheduling @EnableScheduling
@EnableAsync @EnableAsync
@EnableCaching @EnableCaching
@EnableSpringDataWebSupport(pageSerializationMode = PageSerializationMode.VIA_DTO)
public class SpringApp { public class SpringApp {
private final TaskMonitorCenter taskMonitorCenter; private final TaskMonitorCenter taskMonitorCenter;
@@ -230,24 +221,6 @@ public class SpringApp {
} }
} }
// Redis缓存配置已移至application.properties文件
// Spring Boot会根据配置自动创建RedisCacheManager
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ISO_LOCAL_DATE));
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(
DateTimeFormatter.ofPattern(MyDateTimeUtils.DEFAULT_DATETIME_FORMAT_PATTERN)));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ISO_LOCAL_DATE));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(
DateTimeFormatter.ofPattern(MyDateTimeUtils.DEFAULT_DATETIME_FORMAT_PATTERN)));
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ISO_LOCAL_TIME));
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
public static TaskMonitorCenter getTaskMonitorCenter() { public static TaskMonitorCenter getTaskMonitorCenter() {
return getBean(TaskMonitorCenter.class); return getBean(TaskMonitorCenter.class);

View File

@@ -38,8 +38,8 @@ public class AbstractCtx {
return confService; return confService;
} }
public boolean updateText(Supplier<String> getter, Consumer<String> setter, String text, MessageHolder holder,
public boolean updateText(Supplier<String> getter, Consumer<String> setter, String text, MessageHolder holder, String topic) { String topic) {
if (!Objects.equals(getter.get(), text)) { if (!Objects.equals(getter.get(), text)) {
setter.accept(text); setter.accept(text);
holder.info(topic + "修改为: " + text); holder.info(topic + "修改为: " + text);
@@ -48,7 +48,8 @@ public class AbstractCtx {
return false; return false;
} }
public boolean updateAppendText(Supplier<String> getter, Consumer<String> setter, String text, MessageHolder holder, String topic) { public boolean updateAppendText(Supplier<String> getter, Consumer<String> setter, String text, MessageHolder holder,
String topic) {
if (StringUtils.hasText(text)) { if (StringUtils.hasText(text)) {
String str = MyStringUtils.appendIfAbsent(getter.get(), text); String str = MyStringUtils.appendIfAbsent(getter.get(), text);
if (!Objects.equals(getter.get(), str)) { if (!Objects.equals(getter.get(), str)) {
@@ -60,19 +61,21 @@ public class AbstractCtx {
return false; return false;
} }
public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, java.sql.Date date,
public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, java.sql.Date date, MessageHolder holder, String topic) { MessageHolder holder, String topic) {
if (date != null) { if (date != null) {
return updateLocalDate(getter, setter, date.toLocalDate(), holder, topic); return updateLocalDate(getter, setter, date.toLocalDate(), holder, topic);
} }
return false; return false;
} }
public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, LocalDate date, MessageHolder holder, String topic) { public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, LocalDate date,
MessageHolder holder, String topic) {
return updateLocalDate(getter, setter, date, holder, topic, false); return updateLocalDate(getter, setter, date, holder, topic, false);
} }
public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, LocalDate date, MessageHolder holder, String topic, boolean allowNull) { public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, LocalDate date,
MessageHolder holder, String topic, boolean allowNull) {
if (date == null && !allowNull) { if (date == null && !allowNull) {
return false; return false;
} }
@@ -84,7 +87,8 @@ public class AbstractCtx {
return false; return false;
} }
public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, String strDate, MessageHolder holder, String topic) { public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, String strDate,
MessageHolder holder, String topic) {
LocalDate date = null; LocalDate date = null;
if (StringUtils.hasText(strDate)) { if (StringUtils.hasText(strDate)) {
try { try {
@@ -96,7 +100,8 @@ public class AbstractCtx {
return updateLocalDate(getter, setter, date, holder, topic); return updateLocalDate(getter, setter, date, holder, topic);
} }
public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, Timestamp timestamp, MessageHolder holder, String topic) { public boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, Timestamp timestamp,
MessageHolder holder, String topic) {
LocalDate date = null; LocalDate date = null;
if (timestamp != null) { if (timestamp != null) {
@@ -109,7 +114,8 @@ public class AbstractCtx {
return updateLocalDate(getter, setter, date, holder, topic); return updateLocalDate(getter, setter, date, holder, topic);
} }
public boolean updateLocalDateTime(Supplier<LocalDateTime> getter, Consumer<LocalDateTime> setter, Timestamp timestamp, MessageHolder holder, String topic) { public boolean updateLocalDateTime(Supplier<LocalDateTime> getter, Consumer<LocalDateTime> setter,
Timestamp timestamp, MessageHolder holder, String topic) {
LocalDateTime dateTime = null; LocalDateTime dateTime = null;
if (timestamp != null) { if (timestamp != null) {
@@ -121,7 +127,11 @@ public class AbstractCtx {
holder.warn("解析日期" + timestamp + " 异常:" + e.getMessage()); holder.warn("解析日期" + timestamp + " 异常:" + e.getMessage());
} }
} }
return updateLocalDateTime(getter, setter, dateTime, holder, topic);
}
public boolean updateLocalDateTime(Supplier<LocalDateTime> getter, Consumer<LocalDateTime> setter,
LocalDateTime dateTime, MessageHolder holder, String topic) {
if (!Objects.equals(getter.get(), dateTime)) { if (!Objects.equals(getter.get(), dateTime)) {
setter.accept(dateTime); setter.accept(dateTime);
holder.info(topic + "修改为: " + dateTime); holder.info(topic + "修改为: " + dateTime);
@@ -130,7 +140,8 @@ public class AbstractCtx {
return false; return false;
} }
public boolean updateInstant(Supplier<Instant> getter, Consumer<Instant> setter, Instant instant, MessageHolder holder, String topic) { public boolean updateInstant(Supplier<Instant> getter, Consumer<Instant> setter, Instant instant,
MessageHolder holder, String topic) {
if (!Objects.equals(getter.get(), instant)) { if (!Objects.equals(getter.get(), instant)) {
setter.accept(instant); setter.accept(instant);
holder.info(topic + "修改为: " + instant); holder.info(topic + "修改为: " + instant);
@@ -139,13 +150,14 @@ public class AbstractCtx {
return false; return false;
} }
public boolean updateNumber(Supplier<Double> getter, Consumer<Double> setter, BigDecimal value,
public boolean updateNumber(Supplier<Double> getter, Consumer<Double> setter, BigDecimal value, MessageHolder holder, String topic) { MessageHolder holder, String topic) {
double val = value.doubleValue(); double val = value.doubleValue();
return updateNumber(getter, setter, val, holder, topic); return updateNumber(getter, setter, val, holder, topic);
} }
public boolean updateNumber(Supplier<Double> getter, Consumer<Double> setter, double value, MessageHolder holder, String topic) { public boolean updateNumber(Supplier<Double> getter, Consumer<Double> setter, double value, MessageHolder holder,
String topic) {
if (getter.get() == null || !NumberUtils.equals(getter.get(), value)) { if (getter.get() == null || !NumberUtils.equals(getter.get(), value)) {
setter.accept(value); setter.accept(value);
holder.info(topic + "修改为: " + value); holder.info(topic + "修改为: " + value);
@@ -154,7 +166,8 @@ public class AbstractCtx {
return false; return false;
} }
public boolean updateNumber(Supplier<Float> getter, Consumer<Float> setter, float value, MessageHolder holder, String topic) { public boolean updateNumber(Supplier<Float> getter, Consumer<Float> setter, float value, MessageHolder holder,
String topic) {
if (getter.get() == null || !NumberUtils.equals(getter.get(), value)) { if (getter.get() == null || !NumberUtils.equals(getter.get(), value)) {
setter.accept(value); setter.accept(value);
holder.info(topic + "修改为: " + value); holder.info(topic + "修改为: " + value);
@@ -163,8 +176,8 @@ public class AbstractCtx {
return false; return false;
} }
public boolean updateNumber(Supplier<Integer> getter, Consumer<Integer> setter, Integer value, MessageHolder holder,
public boolean updateNumber(Supplier<Integer> getter, Consumer<Integer> setter, Integer value, MessageHolder holder, String topic) { String topic) {
if (getter.get() == null || !NumberUtils.equals(getter.get(), value)) { if (getter.get() == null || !NumberUtils.equals(getter.get(), value)) {
setter.accept(value); setter.accept(value);
holder.info(topic + "修改为: " + value); holder.info(topic + "修改为: " + value);

View File

@@ -5,13 +5,13 @@ import java.io.IOException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.ecep.contract.util.FileUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -36,6 +36,7 @@ import com.ecep.contract.ds.other.service.SysConfService;
import com.ecep.contract.model.CloudRk; import com.ecep.contract.model.CloudRk;
import com.ecep.contract.model.Company; import com.ecep.contract.model.Company;
import com.ecep.contract.model.CompanyBlackReason; import com.ecep.contract.model.CompanyBlackReason;
import com.ecep.contract.util.FileUtils;
import com.ecep.contract.util.HttpJsonUtils; import com.ecep.contract.util.HttpJsonUtils;
import com.ecep.contract.util.MyStringUtils; import com.ecep.contract.util.MyStringUtils;
import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonAlias;
@@ -200,7 +201,7 @@ public class CloudRkService implements IEntityService<CloudRk> {
if (!reasonList.isEmpty()) { if (!reasonList.isEmpty()) {
companyBlackReasonRepository.saveAll(reasonList); companyBlackReasonRepository.saveAll(reasonList);
} }
cloudRk.setCloudBlackListUpdated(Instant.now()); cloudRk.setCloudBlackListUpdated(LocalDateTime.now());
} }
private void toCompanyBlackReasonList( private void toCompanyBlackReasonList(
@@ -234,12 +235,12 @@ public class CloudRkService implements IEntityService<CloudRk> {
*/ */
public boolean checkBlackListUpdateElapse( public boolean checkBlackListUpdateElapse(
Company company, CloudRk cloudRk, BlackListUpdateContext context) { Company company, CloudRk cloudRk, BlackListUpdateContext context) {
Instant start = cloudRk.getCloudBlackListUpdated(); LocalDateTime start = cloudRk.getCloudBlackListUpdated();
if (start == null) { if (start == null) {
return true; return true;
} }
Instant elapse = start.plusSeconds(context.getElapse()); LocalDateTime elapse = start.plusSeconds(context.getElapse());
return elapse.isBefore(Instant.now()); return elapse.isBefore(LocalDateTime.now());
} }
public CloudRk getOrCreateCloudRk(CloudInfo info) { public CloudRk getOrCreateCloudRk(CloudInfo info) {

View File

@@ -1,7 +1,7 @@
package com.ecep.contract.cloud.rk; package com.ecep.contract.cloud.rk;
import java.time.Instant;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
@@ -96,7 +96,7 @@ public class CloudRkSyncTask extends Tasker<Object> {
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} finally { } finally {
cloudRk.setLatestUpdate(Instant.now()); cloudRk.setLatestUpdate(LocalDateTime.now());
service.save(cloudRk); service.save(cloudRk);
} }
// updateProgress(counter.incrementAndGet(), total); // updateProgress(counter.incrementAndGet(), total);

View File

@@ -37,7 +37,6 @@ public class EntReportParser {
private CloudRk cloudRk; private CloudRk cloudRk;
private boolean modified = false; private boolean modified = false;
public void parse(JsonNode json) { public void parse(JsonNode json) {
if (!json.has("B1001")) { if (!json.has("B1001")) {
// 没有数据 // 没有数据
@@ -79,7 +78,6 @@ public class EntReportParser {
} }
private void updateLegalRepresentativeContact(JsonNode data) { private void updateLegalRepresentativeContact(JsonNode data) {
String legalRepresentative = company.getLegalRepresentative(); String legalRepresentative = company.getLegalRepresentative();
if (!StringUtils.hasText(legalRepresentative)) { if (!StringUtils.hasText(legalRepresentative)) {
@@ -94,7 +92,7 @@ public class EntReportParser {
return; return;
} }
if (contactList.isEmpty()) { if (contactList.isEmpty()) {
//没有,创建法人联系人 // 没有,创建法人联系人
contact = new CompanyContact(); contact = new CompanyContact();
contact.setCompany(company); contact.setCompany(company);
contact.setName(legalRepresentative); contact.setName(legalRepresentative);
@@ -107,10 +105,11 @@ public class EntReportParser {
any = contactList.stream().findAny(); any = contactList.stream().findAny();
} }
contact = any.get(); contact = any.get();
// if (contact.getPostion() == null || !contact.setPostion().contains("法定代表人")) { // if (contact.getPostion() == null || !contact.setPostion().contains("法定代表人"))
// contact.setMemo("法定代表人"); // {
// modified = true; // contact.setMemo("法定代表人");
// } // modified = true;
// }
} }
if (!StringUtils.hasText(contact.getEmail())) { if (!StringUtils.hasText(contact.getEmail())) {
@@ -190,7 +189,7 @@ public class EntReportParser {
modified = true; modified = true;
} }
} else { } else {
//fixed 当平台返回的 社会统一信用代码为空时,如果原来已经有的,则不做更新 // fixed 当平台返回的 社会统一信用代码为空时,如果原来已经有的,则不做更新
if (StringUtils.hasText(company.getUniscid())) { if (StringUtils.hasText(company.getUniscid())) {
if (logger.isInfoEnabled()) { if (logger.isInfoEnabled()) {
logger.info("来自平台的 UNISCID 为空,但本地{}已经记录{},不做更改", company.getName(), company.getUniscid()); logger.info("来自平台的 UNISCID 为空,但本地{}已经记录{},不做更改", company.getName(), company.getUniscid());
@@ -212,7 +211,7 @@ public class EntReportParser {
return; return;
} }
LocalDateTime updated = objectMapper.convertValue(node, LocalDateTime.class); LocalDateTime updated = objectMapper.convertValue(node, LocalDateTime.class);
cloudRk.setCloudEntUpdate(updated.toInstant(ZoneOffset.ofHours(8))); cloudRk.setCloudEntUpdate(updated);
} }
private void updateCompanyProperty(String field, JsonNode node, String... excludeValues) { private void updateCompanyProperty(String field, JsonNode node, String... excludeValues) {
@@ -255,7 +254,6 @@ public class EntReportParser {
} }
} }
private void saveJsonToFile(JsonNode json) { private void saveJsonToFile(JsonNode json) {
String companyPath = company.getPath(); String companyPath = company.getPath();
if (StringUtils.hasText(companyPath)) { if (StringUtils.hasText(companyPath)) {

View File

@@ -25,7 +25,6 @@ import java.util.stream.Collectors;
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
import com.ecep.contract.util.FileUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@@ -44,6 +43,7 @@ import com.ecep.contract.model.Company;
import com.ecep.contract.model.CompanyBlackReason; import com.ecep.contract.model.CompanyBlackReason;
import com.ecep.contract.model.CompanyContact; import com.ecep.contract.model.CompanyContact;
import com.ecep.contract.model.CompanyOldName; import com.ecep.contract.model.CompanyOldName;
import com.ecep.contract.util.FileUtils;
import com.ecep.contract.util.HttpJsonUtils; import com.ecep.contract.util.HttpJsonUtils;
import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
@@ -99,8 +99,7 @@ public class CloudRkCtx extends AbstractCtx {
Proxy.Type proxyType = Proxy.Type.valueOf(proxyUri.getScheme().toUpperCase()); Proxy.Type proxyType = Proxy.Type.valueOf(proxyUri.getScheme().toUpperCase());
socksProxy = new Proxy( socksProxy = new Proxy(
proxyType, proxyType,
new InetSocketAddress(proxyUri.getHost(), proxyUri.getPort()) new InetSocketAddress(proxyUri.getHost(), proxyUri.getPort()));
);
} }
return socksProxy; return socksProxy;
} }
@@ -109,7 +108,6 @@ public class CloudRkCtx extends AbstractCtx {
HttpJsonUtils.post(url, data, consumer, getObjectMapper(), getSocksProxy()); HttpJsonUtils.post(url, data, consumer, getObjectMapper(), getSocksProxy());
} }
public boolean syncCompany(Company company, CloudRk cloudRk, MessageHolder holder) { public boolean syncCompany(Company company, CloudRk cloudRk, MessageHolder holder) {
if (!StringUtils.hasText(cloudRk.getCloudId())) { if (!StringUtils.hasText(cloudRk.getCloudId())) {
holder.warn("未定义平台编号, 尝试从平台上自动获取"); holder.warn("未定义平台编号, 尝试从平台上自动获取");
@@ -157,19 +155,17 @@ public class CloudRkCtx extends AbstractCtx {
return updated; return updated;
} }
/** /**
* 更新黑名单列表 * 更新黑名单列表
*/ */
public boolean updateBlackList( public boolean updateBlackList(
Company company, CloudRk cloudRk, MessageHolder holder Company company, CloudRk cloudRk, MessageHolder holder) throws IOException {
) throws IOException { LocalDateTime start = cloudRk.getCloudBlackListUpdated();
Instant start = cloudRk.getCloudBlackListUpdated();
if (start != null) { if (start != null) {
long elapse = getConfService().getLong(CloudRkService.KEY_BLACK_LIST_ELAPSE); long elapse = getConfService().getLong(CloudRkService.KEY_BLACK_LIST_ELAPSE);
if (elapse > 0) { if (elapse > 0) {
Instant next = start.plusSeconds(elapse); LocalDateTime next = start.plusSeconds(elapse);
if (next.isAfter(Instant.now())) { if (next.isAfter(LocalDateTime.now())) {
holder.debug("更新时间未到, 上次更新时间 = " + start); holder.debug("更新时间未到, 上次更新时间 = " + start);
return false; return false;
} }
@@ -179,7 +175,6 @@ public class CloudRkCtx extends AbstractCtx {
String api = getConfService().getString(CloudRkService.KEY_BLACK_LIST_URL); String api = getConfService().getString(CloudRkService.KEY_BLACK_LIST_URL);
List<String> companyNames = getCompanyService().getAllNames(company); List<String> companyNames = getCompanyService().getAllNames(company);
List<CompanyBlackReason> reasonList = new ArrayList<>(); List<CompanyBlackReason> reasonList = new ArrayList<>();
List<CompanyBlackReason> dbReasons = getCompanyBlackReasonService().findAllByCompany(company); List<CompanyBlackReason> dbReasons = getCompanyBlackReasonService().findAllByCompany(company);
for (String name : companyNames) { for (String name : companyNames) {
@@ -195,22 +190,21 @@ public class CloudRkCtx extends AbstractCtx {
} }
if (reasonList.isEmpty()) { if (reasonList.isEmpty()) {
cloudRk.setCloudBlackListUpdated(Instant.now()); cloudRk.setCloudBlackListUpdated(LocalDateTime.now());
return false; return false;
} }
for (CompanyBlackReason companyBlackReason : reasonList) { for (CompanyBlackReason companyBlackReason : reasonList) {
getCompanyBlackReasonService().save(companyBlackReason); getCompanyBlackReasonService().save(companyBlackReason);
} }
cloudRk.setCloudBlackListUpdated(Instant.now()); cloudRk.setCloudBlackListUpdated(LocalDateTime.now());
return true; return true;
} }
private boolean applyBlackReason( private boolean applyBlackReason(
JsonNode json, Company company, CloudRk cloudRk, JsonNode json, Company company, CloudRk cloudRk,
List<CompanyBlackReason> reasonList, List<CompanyBlackReason> dbReasons, List<CompanyBlackReason> reasonList, List<CompanyBlackReason> dbReasons,
MessageHolder holder MessageHolder holder) {
) {
if (isUnSuccess(json, holder)) { if (isUnSuccess(json, holder)) {
return false; return false;
} }
@@ -246,11 +240,11 @@ public class CloudRkCtx extends AbstractCtx {
private void toCompanyBlackReasonList( private void toCompanyBlackReasonList(
Company company, BlackReasonType type, Company company, BlackReasonType type,
JsonNode reason, List<CompanyBlackReason> dbReasons, JsonNode reason, List<CompanyBlackReason> dbReasons,
List<CompanyBlackReason> reasonList List<CompanyBlackReason> reasonList) throws JsonMappingException {
) throws JsonMappingException {
ObjectNode object = (ObjectNode) reason; ObjectNode object = (ObjectNode) reason;
String key = "rk-" + object.remove("id").asText(); String key = "rk-" + object.remove("id").asText();
CompanyBlackReason cbr = dbReasons.stream().filter(r -> r.getKey().equals(key)).findAny().orElseGet(CompanyBlackReason::new); CompanyBlackReason cbr = dbReasons.stream().filter(r -> r.getKey().equals(key)).findAny()
.orElseGet(CompanyBlackReason::new);
getObjectMapper().updateValue(cbr, reason); getObjectMapper().updateValue(cbr, reason);
cbr.setCompany(company); cbr.setCompany(company);
cbr.setType(type); cbr.setType(type);
@@ -258,13 +252,11 @@ public class CloudRkCtx extends AbstractCtx {
reasonList.add(cbr); reasonList.add(cbr);
} }
/** /**
* 更新评分 * 更新评分
*/ */
public boolean updateEnterpriseCredit( public boolean updateEnterpriseCredit(
Company company, CloudRk cloudRk, MessageHolder holder Company company, CloudRk cloudRk, MessageHolder holder) throws IOException {
) throws IOException {
String api = getConfService().getString(CloudRkService.KEY_ENT_SCORE_URL); String api = getConfService().getString(CloudRkService.KEY_ENT_SCORE_URL);
AtomicBoolean modified = new AtomicBoolean(false); AtomicBoolean modified = new AtomicBoolean(false);
try { try {
@@ -332,8 +324,7 @@ public class CloudRkCtx extends AbstractCtx {
* 客户信用 * 客户信用
*/ */
public boolean updateCustomerScore( public boolean updateCustomerScore(
Company company, CloudRk cloudRk, MessageHolder holder Company company, CloudRk cloudRk, MessageHolder holder) throws IOException {
) throws IOException {
String url = getConfService().getString(CloudRkService.KEY_CUSTOMER_REPORT_URL); String url = getConfService().getString(CloudRkService.KEY_CUSTOMER_REPORT_URL);
AtomicBoolean modified = new AtomicBoolean(false); AtomicBoolean modified = new AtomicBoolean(false);
try { try {
@@ -381,16 +372,15 @@ public class CloudRkCtx extends AbstractCtx {
if (updateNumber(cloudRk::getCustomerScore, cloudRk::setCustomerScore, score, holder, "客户信用总分")) { if (updateNumber(cloudRk::getCustomerScore, cloudRk::setCustomerScore, score, holder, "客户信用总分")) {
modified = true; modified = true;
} }
if (updateText(cloudRk::getCustomerDescription, cloudRk::setCustomerDescription, description, holder, "客户信用评级说明")) { if (updateText(cloudRk::getCustomerDescription, cloudRk::setCustomerDescription, description, holder,
"客户信用评级说明")) {
modified = true; modified = true;
} }
return modified; return modified;
} }
public boolean updateVendorScore( public boolean updateVendorScore(
Company company, CloudRk cloudRk, MessageHolder holder Company company, CloudRk cloudRk, MessageHolder holder) throws IOException {
) throws IOException {
String url = getConfService().getString(CloudRkService.KEY_VENDOR_REPORT_URL); String url = getConfService().getString(CloudRkService.KEY_VENDOR_REPORT_URL);
AtomicBoolean modified = new AtomicBoolean(false); AtomicBoolean modified = new AtomicBoolean(false);
try { try {
@@ -437,7 +427,8 @@ public class CloudRkCtx extends AbstractCtx {
if (updateNumber(cloudRk::getVendorScore, cloudRk::setVendorScore, score, holder, "供应商信用总分")) { if (updateNumber(cloudRk::getVendorScore, cloudRk::setVendorScore, score, holder, "供应商信用总分")) {
modified = true; modified = true;
} }
if (updateText(cloudRk::getVendorDescription, cloudRk::setVendorDescription, description, holder, "供应商信用评级说明")) { if (updateText(cloudRk::getVendorDescription, cloudRk::setVendorDescription, description, holder,
"供应商信用评级说明")) {
modified = true; modified = true;
} }
return modified; return modified;
@@ -451,8 +442,7 @@ public class CloudRkCtx extends AbstractCtx {
* @return true 更新了 cloudId否则false * @return true 更新了 cloudId否则false
*/ */
private boolean queryCloudIdAndSelectOne( private boolean queryCloudIdAndSelectOne(
Company company, CloudRk cloudRk, MessageHolder holder Company company, CloudRk cloudRk, MessageHolder holder) {
) {
try { try {
List<CloudRkService.EntInfo> entInfos = queryEnterpriseWithFuzzy(company, cloudRk, holder); List<CloudRkService.EntInfo> entInfos = queryEnterpriseWithFuzzy(company, cloudRk, holder);
// 返回的查询结果为空时 // 返回的查询结果为空时
@@ -464,14 +454,17 @@ public class CloudRkCtx extends AbstractCtx {
} }
// 在返回的结果中,找到与公司名字一致的一个 // 在返回的结果中,找到与公司名字一致的一个
Optional<CloudRkService.EntInfo> optional = entInfos.stream().filter(n -> n.getName().equals(company.getName())).findAny(); Optional<CloudRkService.EntInfo> optional = entInfos.stream()
.filter(n -> n.getName().equals(company.getName())).findAny();
if (optional.isPresent()) { if (optional.isPresent()) {
cloudRk.setCloudId(optional.get().getId()); cloudRk.setCloudId(optional.get().getId());
return true; return true;
} }
// //
holder.error("在平台中查询到多个匹配 (" + entInfos.stream().map(CloudRkService.EntInfo::getName).collect(Collectors.joining(", ")) + "),请手工同步选择匹配"); holder.error("在平台中查询到多个匹配 ("
+ entInfos.stream().map(CloudRkService.EntInfo::getName).collect(Collectors.joining(", "))
+ "),请手工同步选择匹配");
return false; return false;
} catch (Exception e) { } catch (Exception e) {
@@ -484,13 +477,11 @@ public class CloudRkCtx extends AbstractCtx {
} }
} }
/** /**
* 使用模糊查询接口查询相关企业信息 * 使用模糊查询接口查询相关企业信息
*/ */
public List<CloudRkService.EntInfo> queryEnterpriseWithFuzzy( public List<CloudRkService.EntInfo> queryEnterpriseWithFuzzy(
Company company, CloudRk cloudRk, MessageHolder holder Company company, CloudRk cloudRk, MessageHolder holder) throws IOException {
) throws IOException {
String url = getConfService().getString(CloudRkService.KEY_ENT_FUZZY_URL); String url = getConfService().getString(CloudRkService.KEY_ENT_FUZZY_URL);
List<CloudRkService.EntInfo> results = new ArrayList<>(); List<CloudRkService.EntInfo> results = new ArrayList<>();
ObjectMapper objectMapper = getObjectMapper(); ObjectMapper objectMapper = getObjectMapper();
@@ -508,7 +499,8 @@ public class CloudRkCtx extends AbstractCtx {
return results; return results;
} }
private boolean applyEnterpriseQuery(JsonNode json, Company company, CloudRk cloudRk, List<CloudRkService.EntInfo> results, MessageHolder holder) { private boolean applyEnterpriseQuery(JsonNode json, Company company, CloudRk cloudRk,
List<CloudRkService.EntInfo> results, MessageHolder holder) {
if (!json.has("data")) { if (!json.has("data")) {
// 没有数据 // 没有数据
holder.error("数据异常返回的json中没有 data 字段"); holder.error("数据异常返回的json中没有 data 字段");
@@ -542,8 +534,7 @@ public class CloudRkCtx extends AbstractCtx {
* 更新企业工商注册信息 * 更新企业工商注册信息
*/ */
public boolean updateEnterpriseInfo( public boolean updateEnterpriseInfo(
Company company, CloudRk cloudRk, MessageHolder holder Company company, CloudRk cloudRk, MessageHolder holder) throws IOException {
) throws IOException {
String api = getConfService().getString(CloudRkService.KEY_ENT_REPORT_URL); String api = getConfService().getString(CloudRkService.KEY_ENT_REPORT_URL);
Proxy socksProxy = getSocksProxy(); Proxy socksProxy = getSocksProxy();
holder.debug("更新企业工商注册信息: " + company.getName() + " @ " + api + ", proxy=" + socksProxy); holder.debug("更新企业工商注册信息: " + company.getName() + " @ " + api + ", proxy=" + socksProxy);
@@ -609,10 +600,12 @@ public class CloudRkCtx extends AbstractCtx {
if (updateText(company::getRegisteredCapital, company::setRegisteredCapital, data, "regcap", holder, "注册资金")) { if (updateText(company::getRegisteredCapital, company::setRegisteredCapital, data, "regcap", holder, "注册资金")) {
modified = true; modified = true;
} }
if (updateText(company::getRegisteredCapitalCurrency, company::setRegisteredCapitalCurrency, data, "regcapcur", holder, "资本金币种")) { if (updateText(company::getRegisteredCapitalCurrency, company::setRegisteredCapitalCurrency, data, "regcapcur",
holder, "资本金币种")) {
modified = true; modified = true;
} }
if (updateText(company::getLegalRepresentative, company::setLegalRepresentative, data, "frname", holder, "法人")) { if (updateText(company::getLegalRepresentative, company::setLegalRepresentative, data, "frname", holder,
"法人")) {
modified = true; modified = true;
} }
if (updateText(company::getDistrict, company::setDistrict, data, "regorgprovince", holder, "注册区域")) { if (updateText(company::getDistrict, company::setDistrict, data, "regorgprovince", holder, "注册区域")) {
@@ -636,10 +629,21 @@ public class CloudRkCtx extends AbstractCtx {
updateCompanyNameHistory(company, data, holder.sub("曾用名")); updateCompanyNameHistory(company, data, holder.sub("曾用名"));
updateLegalRepresentativeContact(company, data, holder.sub("法人联系方式")); updateLegalRepresentativeContact(company, data, holder.sub("法人联系方式"));
updateInstant(cloudRk::getCloudEntUpdate, cloudRk::setCloudEntUpdate, data, "updated", holder, "更新时间", false);
updateLocalDateTime(cloudRk::getCloudEntUpdate, cloudRk::setCloudEntUpdate, data, "updated", holder, "更新时间");
return modified; return modified;
} }
public boolean updateLocalDateTime(Supplier<LocalDateTime> getter, Consumer<LocalDateTime> setter, JsonNode data,String field,
MessageHolder holder, String topic) {
JsonNode node = data.get(field);
if (node == null || node.isNull()) {
return false;
}
LocalDateTime updated = getObjectMapper().convertValue(node, LocalDateTime.class);
updateLocalDateTime(getter, setter, updated, holder, topic);
return false;
}
/** /**
* 更新法人联系人联系方式 * 更新法人联系人联系方式
@@ -650,7 +654,6 @@ public class CloudRkCtx extends AbstractCtx {
return; return;
} }
CompanyContactService contactService = SpringApp.getBean(CompanyContactService.class); CompanyContactService contactService = SpringApp.getBean(CompanyContactService.class);
List<CompanyContact> contactList = contactService.findAllByCompanyAndName(company, legalRepresentative); List<CompanyContact> contactList = contactService.findAllByCompanyAndName(company, legalRepresentative);
if (contactList == null) { if (contactList == null) {
@@ -660,7 +663,7 @@ public class CloudRkCtx extends AbstractCtx {
CompanyContact contact = null; CompanyContact contact = null;
boolean modified = false; boolean modified = false;
if (contactList.isEmpty()) { if (contactList.isEmpty()) {
//没有,创建法人联系人 // 没有,创建法人联系人
contact = new CompanyContact(); contact = new CompanyContact();
contact.setCompany(company); contact.setCompany(company);
contact.setName(legalRepresentative); contact.setName(legalRepresentative);
@@ -705,7 +708,8 @@ public class CloudRkCtx extends AbstractCtx {
} }
private boolean updateOperationPeriodBegin(Company company, JsonNode data, MessageHolder holder) { private boolean updateOperationPeriodBegin(Company company, JsonNode data, MessageHolder holder) {
return updateLocalDate(company::getOperationPeriodBegin, company::setOperationPeriodBegin, data, "opfrom", holder, "营业期限起始日期", true); return updateLocalDate(company::getOperationPeriodBegin, company::setOperationPeriodBegin, data, "opfrom",
holder, "营业期限起始日期", true);
} }
private boolean updateOperationPeriodEnd(Company company, JsonNode data, MessageHolder holder) { private boolean updateOperationPeriodEnd(Company company, JsonNode data, MessageHolder holder) {
@@ -716,14 +720,15 @@ public class CloudRkCtx extends AbstractCtx {
String text = node.asText(); String text = node.asText();
if (StringUtils.hasText(text)) { if (StringUtils.hasText(text)) {
if (text.equals("-")) { if (text.equals("-")) {
return updateLocalDate(company::getOperationPeriodEnd, company::setOperationPeriodEnd, (LocalDate) null, holder, "营业期限截至日期", true); return updateLocalDate(company::getOperationPeriodEnd, company::setOperationPeriodEnd, (LocalDate) null,
holder, "营业期限截至日期", true);
} }
return updateLocalDate(company::getOperationPeriodEnd, company::setOperationPeriodEnd, data, "opto", holder, "营业期限截至日期", true); return updateLocalDate(company::getOperationPeriodEnd, company::setOperationPeriodEnd, data, "opto", holder,
"营业期限截至日期", true);
} }
return false; return false;
} }
private void updateCompanyNameHistory(Company company, JsonNode data, MessageHolder holder) { private void updateCompanyNameHistory(Company company, JsonNode data, MessageHolder holder) {
JsonNode node = data.get("nameHistory"); JsonNode node = data.get("nameHistory");
if (node == null) { if (node == null) {
@@ -754,7 +759,8 @@ public class CloudRkCtx extends AbstractCtx {
} }
} }
private boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, JsonNode data, String field, MessageHolder holder, String topic, boolean allowNull) { private boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, JsonNode data, String field,
MessageHolder holder, String topic, boolean allowNull) {
JsonNode node = data.get(field); JsonNode node = data.get(field);
if (node == null || node.isNull()) { if (node == null || node.isNull()) {
return false; return false;
@@ -766,11 +772,13 @@ public class CloudRkCtx extends AbstractCtx {
return updateLocalDate(getter, setter, localDate, holder, topic, allowNull); return updateLocalDate(getter, setter, localDate, holder, topic, allowNull);
} }
private boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, JsonNode data, String field, MessageHolder holder, String topic) { private boolean updateLocalDate(Supplier<LocalDate> getter, Consumer<LocalDate> setter, JsonNode data, String field,
MessageHolder holder, String topic) {
return updateLocalDate(getter, setter, data, field, holder, topic, false); return updateLocalDate(getter, setter, data, field, holder, topic, false);
} }
private void updateInstant(Supplier<Instant> getter, Consumer<Instant> setter, JsonNode data, String field, MessageHolder holder, String topic, boolean allowNull) { private void updateInstant(Supplier<Instant> getter, Consumer<Instant> setter, JsonNode data, String field,
MessageHolder holder, String topic, boolean allowNull) {
JsonNode node = data.get("updated"); JsonNode node = data.get("updated");
if (node == null) { if (node == null) {
return; return;
@@ -787,7 +795,8 @@ public class CloudRkCtx extends AbstractCtx {
updateInstant(getter, setter, instant, holder, topic); updateInstant(getter, setter, instant, holder, topic);
} }
private boolean updateText(Supplier<String> getter, Consumer<String> setter, JsonNode data, String field, MessageHolder holder, String topic) { private boolean updateText(Supplier<String> getter, Consumer<String> setter, JsonNode data, String field,
MessageHolder holder, String topic) {
JsonNode node = data.get(field); JsonNode node = data.get(field);
if (node == null || node.isNull()) { if (node == null || node.isNull()) {
return false; return false;

View File

@@ -0,0 +1,160 @@
package com.ecep.contract.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
import java.util.HashMap;
import java.util.Map;
/**
* 全局异常处理器捕获并处理所有Controller层抛出的异常将错误信息以JSON格式返回给前端
*/
// @RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理所有未捕获的异常
*/
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleException(Exception e) {
logger.error("系统异常", e);
Map<String, Object> result = new HashMap<>();
result.put("code", 500);
result.put("message", "系统内部错误:" + e.getMessage());
result.put("errorType", e.getClass().getName());
result.put("success", false);
return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
}
/**
* 处理运行时异常
*/
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<Map<String, Object>> handleRuntimeException(RuntimeException e) {
logger.error("运行时异常", e);
Map<String, Object> result = new HashMap<>();
result.put("code", 500);
result.put("message", "运行时错误:" + e.getMessage());
result.put("errorType", e.getClass().getName());
result.put("success", false);
return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
}
/**
* 处理请求方法不支持异常
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResponseEntity<Map<String, Object>> handleHttpRequestMethodNotSupportedException(
HttpRequestMethodNotSupportedException e) {
logger.warn("请求方法不支持", e);
Map<String, Object> result = new HashMap<>();
result.put("code", 405);
result.put("message", "请求方法不支持:" + e.getMessage());
result.put("errorType", "MethodNotAllowed");
result.put("success", false);
return new ResponseEntity<>(result, HttpStatus.METHOD_NOT_ALLOWED);
}
/**
* 处理资源未找到异常
*/
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<Map<String, Object>> handleNoHandlerFoundException(NoHandlerFoundException e) {
logger.warn("资源未找到", e);
Map<String, Object> result = new HashMap<>();
result.put("code", 404);
result.put("message", "请求的资源不存在:" + e.getRequestURL());
result.put("errorType", "ResourceNotFound");
result.put("success", false);
return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
}
/**
* 处理参数绑定异常
*/
@ExceptionHandler(BindException.class)
public ResponseEntity<Map<String, Object>> handleBindException(BindException e) {
logger.warn("参数绑定异常", e);
Map<String, Object> result = new HashMap<>();
result.put("code", 400);
result.put("message", "参数绑定错误:" + e.getAllErrors().get(0).getDefaultMessage());
result.put("errorType", "ParameterBindingError");
result.put("success", false);
return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
}
/**
* 处理方法参数验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> handleMethodArgumentNotValidException(
MethodArgumentNotValidException e) {
logger.warn("方法参数验证异常", e);
Map<String, Object> result = new HashMap<>();
result.put("code", 400);
result.put("message", "参数验证错误:" + e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
result.put("errorType", "ParameterValidationError");
result.put("success", false);
return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
}
/**
* 处理缺少请求参数异常
*/
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<Map<String, Object>> handleMissingServletRequestParameterException(
MissingServletRequestParameterException e) {
logger.warn("缺少请求参数异常", e);
Map<String, Object> result = new HashMap<>();
result.put("code", 400);
result.put("message", "缺少必要参数:" + e.getParameterName());
result.put("errorType", "MissingParameter");
result.put("success", false);
return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
}
/**
* 处理方法参数类型不匹配异常
*/
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<Map<String, Object>> handleMethodArgumentTypeMismatchException(
MethodArgumentTypeMismatchException e) {
logger.warn("方法参数类型不匹配异常", e);
Map<String, Object> result = new HashMap<>();
result.put("code", 400);
result.put("message", "参数类型错误:参数 '" + e.getName() + "' 应类型为 "
+ (e.getRequiredType() != null ? e.getRequiredType().getSimpleName() : "未知类型"));
result.put("errorType", "ParameterTypeError");
result.put("success", false);
return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
}
/**
* 处理HTTP消息不可读异常如JSON解析错误
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<Map<String, Object>> handleHttpMessageNotReadableException(
HttpMessageNotReadableException e) {
logger.warn("HTTP消息不可读异常", e);
Map<String, Object> result = new HashMap<>();
result.put("code", 400);
result.put("message", "请求体格式错误:" + e.getMessage());
result.put("errorType", "MessageFormatError");
result.put("success", false);
return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
}
}

View File

@@ -0,0 +1,239 @@
package com.ecep.contract.config;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Collections;
import org.hibernate.Hibernate;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.proxy.HibernateProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import com.ecep.contract.model.IdentityEntity;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
/**
* Jackson配置类用于配置JSON序列化相关的设置解决循环引用问题
*/
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.build();
// 关闭日期时间格式化输出为时间戳而是输出为ISO格式的字符串
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// 配置处理循环引用的策略使用INDENT_OUTPUT格式化输出
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
// 处理循环引用,启用引用处理功能
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
// 配置Java 8时间模块的序列化格式
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ISO_LOCAL_DATE));
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ISO_LOCAL_DATE));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ISO_LOCAL_TIME));
objectMapper.registerModule(javaTimeModule);
// 添加自定义模块用于处理JPA/Hibernate代理对象
SimpleModule proxyModule = new SimpleModule("HibernateProxyModule");
// 添加代理对象序列化器只输出ID字段
proxyModule.addSerializer(HibernateProxy.class, new HibernateProxySerializer());
// 使用BeanSerializerModifier来处理IdentityEntity类型避免递归调用
proxyModule.setSerializerModifier(new BeanSerializerModifier() {
@Override
public JsonSerializer<?> modifySerializer(SerializationConfig config,
BeanDescription beanDesc,
JsonSerializer<?> serializer) {
// 只对IdentityEntity类型进行修改
if (IdentityEntity.class.isAssignableFrom(beanDesc.getBeanClass()) &&
!HibernateProxy.class.isAssignableFrom(beanDesc.getBeanClass())) {
return new IdentityEntitySerializer(serializer);
}
return serializer;
}
});
objectMapper.registerModule(proxyModule);
return objectMapper;
}
/**
* 专门用于处理Hibernate代理对象的序列化器
*/
private static class HibernateProxySerializer extends StdSerializer<HibernateProxy> {
protected HibernateProxySerializer() {
super(HibernateProxy.class);
}
@Override
public void serialize(HibernateProxy value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
// 尝试初始化代理对象如果未初始化则只输出ID
try {
Object unwrapped = value.getHibernateLazyInitializer().getImplementation();
// 检查是否为IdentityEntity实现类
if (unwrapped instanceof IdentityEntity) {
gen.writeStartObject();
gen.writeNumberField("id", ((IdentityEntity) unwrapped).getId());
gen.writeEndObject();
} else {
// 如果不是IdentityEntity使用默认序列化
serializers.defaultSerializeValue(unwrapped, gen);
}
} catch (Exception e) {
// 如果初始化失败只输出ID
if (value instanceof IdentityEntity) {
gen.writeStartObject();
gen.writeNumberField("id", ((IdentityEntity) value).getId());
gen.writeEndObject();
} else {
// 如果不是IdentityEntity输出对象的基本信息
gen.writeStartObject();
gen.writeStringField("class", value.getClass().getName());
gen.writeEndObject();
}
}
}
}
/**
* 用于处理集合类型的序列化器,避免懒加载集合在会话关闭时无法序列化的问题
*/
private static class CollectionSerializer extends StdSerializer<Collection<?>> {
protected CollectionSerializer() {
super((Class<Collection<?>>) (Class<?>) Collection.class);
}
@Override
public void serialize(Collection<?> value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
// 检查集合是否为Hibernate的持久化集合
if (value instanceof PersistentCollection) {
PersistentCollection persistentCollection = (PersistentCollection) value;
// 如果集合未初始化,返回空集合
if (!persistentCollection.wasInitialized()) {
gen.writeStartArray();
gen.writeEndArray();
return;
}
}
// 如果已初始化,使用默认序列化
serializers.defaultSerializeValue(value, gen);
}
}
/**
* 用于处理IdentityEntity类型的序列化器包装器
*/
private static class IdentityEntitySerializer extends StdSerializer<Object> {
private final JsonSerializer<?> delegate;
protected IdentityEntitySerializer(JsonSerializer<?> delegate) {
super(Object.class);
this.delegate = delegate;
}
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
// 对于IdentityEntity对象如果未初始化则只输出ID
if (value instanceof IdentityEntity && !Hibernate.isInitialized(value)) {
gen.writeStartObject();
gen.writeNumberField("id", ((IdentityEntity) value).getId());
gen.writeStringField("_proxy_", value.getClass().getName());
gen.writeEndObject();
} else {
// 已初始化的实体,使用原始的序列化器进行序列化,避免递归调用
((JsonSerializer<Object>) delegate).serialize(value, gen, serializers);
}
}
}
/**
* 用于处理对象引用的序列化器,通过检测和管理对象引用避免循环引用问题
*/
private static class IdentityReferenceSerializer extends StdSerializer<Object> {
private final JsonSerializer<?> delegate;
private final ThreadLocal<java.util.Set<Object>> visitedObjects = ThreadLocal
.withInitial(java.util.HashSet::new);
protected IdentityReferenceSerializer(JsonSerializer<?> delegate) {
super(Object.class);
this.delegate = delegate;
}
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
// 处理null值
if (value == null) {
serializers.defaultSerializeNull(gen);
return;
}
java.util.Set<Object> visited = visitedObjects.get();
try {
// 检查对象是否已经被访问过
if (visited.contains(value)) {
// 如果对象实现了IdentityEntity只输出ID
if (value instanceof IdentityEntity) {
gen.writeStartObject();
gen.writeNumberField("id", ((IdentityEntity) value).getId());
gen.writeStringField("_ref_", "" + ((IdentityEntity) value).getId());
gen.writeEndObject();
} else {
// 对于非IdentityEntity对象输出对象的toString或hashCode
gen.writeString(value.toString());
}
return;
}
// 标记对象为已访问
visited.add(value);
// 使用委托序列化器进行正常序列化
((JsonSerializer<Object>) delegate).serialize(value, gen, serializers);
} finally {
// 清理访问记录
visited.remove(value);
if (visited.isEmpty()) {
visitedObjects.remove();
}
}
}
}
}

View File

@@ -8,8 +8,9 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
@@ -22,7 +23,6 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.config.Customizer;
import com.ecep.contract.ds.other.service.EmployeeService; import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.model.Employee; import com.ecep.contract.model.Employee;
@@ -34,6 +34,7 @@ import com.ecep.contract.model.EmployeeRole;
*/ */
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true) // 开启 @PreAuthorize 等注解
public class SecurityConfig { public class SecurityConfig {
@Lazy @Lazy
@@ -45,10 +46,13 @@ public class SecurityConfig {
* 启用表单登录和HTTP Basic认证 * 启用表单登录和HTTP Basic认证
*/ */
@Bean @Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception { public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationManager authenticationManager)
throws Exception {
http http
.authorizeHttpRequests(authorize -> authorize .authorizeHttpRequests(authorize -> authorize
.requestMatchers("/login.html", "/css/**", "/js/**", "/images/**", "/webjars/**", "/login", "/error").permitAll() // 允许静态资源、登录页面和错误页面访问 .requestMatchers("/login.html", "/css/**", "/js/**", "/images/**", "/webjars/**", "/login",
"/error")
.permitAll() // 允许静态资源、登录页面和错误页面访问
.anyRequest().authenticated() // 其他所有请求需要认证 .anyRequest().authenticated() // 其他所有请求需要认证
) )
.csrf(AbstractHttpConfigurer::disable) // 禁用CSRF保护适合开发环境 .csrf(AbstractHttpConfigurer::disable) // 禁用CSRF保护适合开发环境
@@ -84,7 +88,8 @@ public class SecurityConfig {
* 用于处理认证请求 * 用于处理认证请求
*/ */
@Bean @Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager(); return authenticationConfiguration.getAuthenticationManager();
} }
@@ -118,7 +123,8 @@ public class SecurityConfig {
} }
// 将员工角色转换为Spring Security的GrantedAuthority // 将员工角色转换为Spring Security的GrantedAuthority
List<GrantedAuthority> authorities = getAuthoritiesFromRoles(employee.getRoles()); List<GrantedAuthority> authorities = getAuthoritiesFromRoles(
employeeService.getRolesByEmployeeId(employee.getId()));
// 创建并返回UserDetails对象 // 创建并返回UserDetails对象
// 注意根据系统设计Employee实体中没有密码字段系统使用IP/MAC绑定认证 // 注意根据系统设计Employee实体中没有密码字段系统使用IP/MAC绑定认证
@@ -155,6 +161,7 @@ public class SecurityConfig {
// Spring Security会自动配置一个使用我们定义的UserDetailsService的DaoAuthenticationProvider // Spring Security会自动配置一个使用我们定义的UserDetailsService的DaoAuthenticationProvider
// 移除显式的authenticationProvider Bean定义以避免警告 // 移除显式的authenticationProvider Bean定义以避免警告
// 当同时存在AuthenticationProvider和UserDetailsService Bean时Spring Security会优先使用AuthenticationProvider // 当同时存在AuthenticationProvider和UserDetailsService Bean时Spring
// Security会优先使用AuthenticationProvider
// 而忽略直接的UserDetailsService虽然这不影响功能但会产生警告 // 而忽略直接的UserDetailsService虽然这不影响功能但会产生警告
} }

View File

@@ -5,7 +5,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
/** /**
* 基础控制器,处理根路径请求和错误处理 * 基础控制器,处理根路径请求
*/ */
@RestController @RestController
public class IndexController { public class IndexController {
@@ -18,11 +18,4 @@ public class IndexController {
return ResponseEntity.ok("合同管理系统 REST API 服务已启动"); return ResponseEntity.ok("合同管理系统 REST API 服务已启动");
} }
/**
* 处理错误路径请求避免Whitelabel Error Page显示
*/
@GetMapping("/error")
public ResponseEntity<?> error() {
return ResponseEntity.status(404).body("请求的资源不存在");
}
} }

View File

@@ -2,6 +2,7 @@ package com.ecep.contract.ds.company.tasker;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -76,7 +77,7 @@ public class CompanyCompositeUpdateTasker extends Tasker<Object> {
} catch (Exception e) { } catch (Exception e) {
cloudRk.setDescription(e.getMessage()); cloudRk.setDescription(e.getMessage());
} finally { } finally {
cloudRk.setLatestUpdate(Instant.now()); cloudRk.setLatestUpdate(LocalDateTime.now());
cloudRkService.save(cloudRk); cloudRkService.save(cloudRk);
} }
} }

View File

@@ -0,0 +1,51 @@
package com.ecep.contract.ds.other.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ecep.contract.ds.other.service.BankService;
import com.ecep.contract.model.Bank;
@RestController
@RequestMapping("/bank")
public class BankController {
@Autowired
private BankService bankService;
@RequestMapping("/findById")
public Bank findById(Integer id) {
return bankService.findById(id);
}
@RequestMapping("/list")
public Page<Bank> list(
Map<String, Object> params,
@RequestParam(defaultValue = "0", name = "page") int pageNumber,
@RequestParam(defaultValue = "10", name = "size") int pageSize) {
Specification<Bank> spec = null;
Sort sort = Sort.by(Sort.Order.desc("id"));
Pageable pageable = PageRequest.of(pageNumber, pageSize, sort);
// PagedModel<Bank> pagedModel = new PagedModel<>();
return bankService.findAll(spec, pageable);
}
@RequestMapping("/save")
public Bank save(Bank bank) {
return bankService.save(bank);
}
@RequestMapping("/delete")
public void delete(Integer id) {
Bank bank = bankService.findById(id);
bankService.delete(bank);
}
}

View File

@@ -14,10 +14,11 @@ import org.springframework.web.bind.annotation.RestController;
import com.ecep.contract.ds.other.service.EmployeeService; import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.model.Employee; import com.ecep.contract.model.Employee;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@RestController @RestController
@RequestMapping("/employee") @RequestMapping("/employee")
public class EmployyeController { public class EmployeeController {
@Autowired @Autowired
private EmployeeService employeeService; private EmployeeService employeeService;
@@ -29,9 +30,9 @@ public class EmployyeController {
@RequestMapping("/list") @RequestMapping("/list")
public Page<Employee> list( public Page<Employee> list(
Map<String, Object> params, Map<String, Object> params,
@RequestParam(defaultValue = "0") int pageNumber, @RequestParam(defaultValue = "0", name = "page") int pageNumber,
@RequestParam(defaultValue = "10") int pageSize) { @RequestParam(defaultValue = "10") int pageSize) {
Specification<Employee> spec = (root, query, cb) -> cb.conjunction(); Specification<Employee> spec = null;
Sort sort = Sort.by(Sort.Order.desc("id")); Sort sort = Sort.by(Sort.Order.desc("id"));
Pageable pageable = PageRequest.of(pageNumber, pageSize, sort); Pageable pageable = PageRequest.of(pageNumber, pageSize, sort);
return employeeService.findAll(spec, pageable); return employeeService.findAll(spec, pageable);

View File

@@ -51,6 +51,7 @@ public class EmployeeService implements IEntityService<Employee> {
// 从员工仓库中根据ID查找员工信息如果不存在则返回null // 从员工仓库中根据ID查找员工信息如果不存在则返回null
return employeeRepository.findById(id).orElse(null); return employeeRepository.findById(id).orElse(null);
} }
@Cacheable(key = "'ac-'+#p0") @Cacheable(key = "'ac-'+#p0")
public Employee findByAccount(String username) { public Employee findByAccount(String username) {
return employeeRepository.findByAccount(username).orElse(null); return employeeRepository.findByAccount(username).orElse(null);
@@ -155,4 +156,6 @@ public class EmployeeService implements IEntityService<Employee> {
return null; return null;
} }
} }

View File

@@ -35,13 +35,24 @@ logging.level.org.hibernate.tool.hbm2ddl=DEBUG
logging.level.org.springframework.boot.context.metrics.buffering=DEBUG logging.level.org.springframework.boot.context.metrics.buffering=DEBUG
logging.level.com.ecep.contract.manager.SpringApp=DEBUG logging.level.com.ecep.contract.manager.SpringApp=DEBUG
# JSON序列化错误调试日志
logging.level.org.springframework.http.converter=DEBUG
logging.level.com.fasterxml.jackson=TRACE
logging.level.org.springframework.web.servlet.mvc.method.annotation=TRACE
# Redis缓存配置 # Redis缓存配置
spring.cache.type=redis spring.cache.type=redis
spring.cache.redis.time-to-live=6h spring.cache.redis.time-to-live=6h
spring.cache.redis.key-prefix=contract_manager_ spring.cache.redis.key-prefix=contract_manager_
spring.cache.redis.use-key-prefix=true spring.cache.redis.use-key-prefix=true
spring.cache.redis.cache-null-values=false spring.cache.redis.cache-null-values=true
# Redis序列化配置 # Redis序列化配置
spring.data.redis.serializer.key=org.springframework.data.redis.serializer.StringRedisSerializer spring.data.redis.serializer.key=org.springframework.data.redis.serializer.StringRedisSerializer
spring.data.redis.serializer.value=org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer spring.data.redis.serializer.value=org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer
# 禁用默认的Whitelabel错误页面
server.error.whitelabel.enabled=false
# 设置错误处理路径确保404等错误能被全局异常处理器捕获
spring.mvc.throw-exception-if-no-handler-found=true
spring.web.resources.add-mappings=true