This commit is contained in:
2025-11-19 16:10:25 +08:00
parent 9aa041c479
commit 5a77756c33
25 changed files with 238 additions and 90 deletions

View File

@ -15,6 +15,8 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.IOException; import java.io.IOException;
import static com.yj.earth.datasource.DatabaseManager.initializeDatabasePath;
@Slf4j @Slf4j
@EnableAspectJAutoProxy @EnableAspectJAutoProxy
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@ -27,14 +29,10 @@ public class ServerApp implements CommandLineRunner {
private ServerInitService serverInitService; private ServerInitService serverInitService;
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
// 提前初始化数据库路径
initializeDatabasePath();
// 启动项目SDK服务 // 启动项目SDK服务
SdkUtil.startSdkIfConfigured(); SdkUtil.startSdkIfConfigured();
// 初始化数据库相关操作
String activeDataSource = DatabaseManager.getActiveDataSource();
// 获取数据库类型
DatabaseManager.DatabaseType dbType = DatabaseManager.DatabaseType.valueOf(activeDataSource.toUpperCase());
// 初始化数据库
DatabaseManager.initDatabase(dbType);
// 启动应用服务 // 启动应用服务
SpringApplication application = new SpringApplication(ServerApp.class); SpringApplication application = new SpringApplication(ServerApp.class);
// 允许循环引用 // 允许循环引用
@ -45,6 +43,12 @@ public class ServerApp implements CommandLineRunner {
@Override @Override
public void run(String... args) throws Exception { public void run(String... args) throws Exception {
// 初始化数据库相关操作
String activeDataSource = DatabaseManager.getActiveDataSource();
// 获取数据库类型
DatabaseManager.DatabaseType dbType = DatabaseManager.DatabaseType.valueOf(activeDataSource.toUpperCase());
// 初始化数据库
DatabaseManager.initDatabase(dbType);
// 初始化资源 // 初始化资源
serverInitService.init(); serverInitService.init();
// 检查默认数据 // 检查默认数据

View File

@ -77,7 +77,7 @@ public class AuthGenerator {
public static void main(String[] args) { public static void main(String[] args) {
try { try {
// 生成加密的授权字符串 // 生成加密的授权字符串
String authContent = generateAuth("标准版", 1000, 7, "25F429FDA965007B72BB7A6B2C03535A"); String authContent = generateAuth("标准版", 1000, 365, "196CB2226A5D5334B9C065ECFC77F4B9");
// 定义授权文件路径(当前目录下的 yjearth.lic // 定义授权文件路径(当前目录下的 yjearth.lic
Path licPath = Paths.get("yjearth.lic"); Path licPath = Paths.get("yjearth.lic");

View File

@ -14,7 +14,7 @@ import javax.annotation.Resource;
@Tag(name = "业务配置管理") @Tag(name = "业务配置管理")
@CheckAuth
@RestController @RestController
@RequestMapping("/businessConfig") @RequestMapping("/businessConfig")
public class BusinessConfigController { public class BusinessConfigController {

View File

@ -45,7 +45,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
@Tag(name = "文件数据管理") @Tag(name = "文件数据管理")
@CheckAuth
@RestController @RestController
@RequestMapping("/fileInfo") @RequestMapping("/fileInfo")
public class FileInfoController { public class FileInfoController {

View File

@ -10,6 +10,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@ -27,7 +28,6 @@ public class GdalController {
@Operation(summary = "导入矢量数据") @Operation(summary = "导入矢量数据")
@PostMapping("/import") @PostMapping("/import")
public void importDataStreamGzip(@Parameter(description = "矢量文件路径", required = true) @RequestParam("path") String path, HttpServletResponse response) throws IOException { public void importDataStreamGzip(@Parameter(description = "矢量文件路径", required = true) @RequestParam("path") String path, HttpServletResponse response) throws IOException {
// 解析矢量文件、得到JSON数据 // 解析矢量文件、得到JSON数据
String jsonData = GdalJsonConverter.convertToJson(path); String jsonData = GdalJsonConverter.convertToJson(path);
@ -38,8 +38,7 @@ public class GdalController {
response.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
// 使用GZIP压缩并输出 // 使用GZIP压缩并输出
try (OutputStream outputStream = response.getOutputStream(); try (OutputStream outputStream = response.getOutputStream(); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream)) {
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream)) {
gzipOutputStream.write(jsonData.getBytes(StandardCharsets.UTF_8)); gzipOutputStream.write(jsonData.getBytes(StandardCharsets.UTF_8));
gzipOutputStream.finish(); gzipOutputStream.finish();
} }

View File

@ -38,7 +38,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
@Data @Data
@Slf4j @Slf4j
@Tag(name = "路径规划管理") @Tag(name = "路径规划管理")
@CheckAuth
@RestController @RestController
@RequestMapping("/graphhopper") @RequestMapping("/graphhopper")
public class GraphHopperController { public class GraphHopperController {
@ -58,7 +58,7 @@ public class GraphHopperController {
@Operation(summary = "加载地图数据") @Operation(summary = "加载地图数据")
@PostMapping("/loadMap") @PostMapping("/loadMap")
@CheckAuth
public ApiResponse loadMap(@Parameter(description = "文件路径") @RequestParam String path) { public ApiResponse loadMap(@Parameter(description = "文件路径") @RequestParam String path) {
File osmFile = new File(path); File osmFile = new File(path);
if (!osmFile.exists()) { if (!osmFile.exists()) {
@ -108,7 +108,7 @@ public class GraphHopperController {
@Operation(summary = "清除地图服务") @Operation(summary = "清除地图服务")
@PostMapping("/clearMap") @PostMapping("/clearMap")
@CheckAuth
public ApiResponse clearMap() { public ApiResponse clearMap() {
// 防止并发操作(与加载操作互斥) // 防止并发操作(与加载操作互斥)
if (isLoading.get()) { if (isLoading.get()) {
@ -146,11 +146,14 @@ public class GraphHopperController {
@Operation(summary = "路径规划") @Operation(summary = "路径规划")
@PostMapping("/route") @PostMapping("/route")
@CheckAuth
public ApiResponse calculateRoute(@RequestBody RouteRequest request) { public ApiResponse calculateRoute(@RequestBody RouteRequest request) {
// 校验地图是否加载完成 + 实例是否可用 // 区分未加载地图和加载中两种状态
if (isLoading.get()) {
return ApiResponse.failure("地图正在加载中,请稍后再试");
}
if (!isLoaded.get() || currentHopper == null) { if (!isLoaded.get() || currentHopper == null) {
return ApiResponse.failure("地图未加载完成"); return ApiResponse.failure("地图未加载,请先加载地图");
} }
try { try {
// 构建路径点列表 // 构建路径点列表
@ -203,8 +206,20 @@ public class GraphHopperController {
} }
} }
@Operation(summary = "获取地图加载状态")
@GetMapping("/status")
public ApiResponse getMapStatus() {
if (isLoading.get()) {
return ApiResponse.success("地图正在加载中");
} else if (isLoaded.get() && currentHopper != null) {
return ApiResponse.success("地图已加载完成");
} else {
return ApiResponse.success("地图未加载");
}
}
@Operation(summary = "获取交通方式") @Operation(summary = "获取交通方式")
@CheckAuth
@PostMapping("/profiles") @PostMapping("/profiles")
public ApiResponse profiles() { public ApiResponse profiles() {
return ApiResponse.success(graphHopperProperties.getProfiles()); return ApiResponse.success(graphHopperProperties.getProfiles());

View File

@ -42,7 +42,7 @@ import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Tag(name = "图标数据管理") @Tag(name = "图标数据管理")
@CheckAuth
@RestController @RestController
@RequestMapping("/iconLibrary") @RequestMapping("/iconLibrary")
public class IconLibraryController { public class IconLibraryController {

View File

@ -28,8 +28,17 @@ public class MatterController {
@PostMapping("/add") @PostMapping("/add")
@Operation(summary = "添加物资") @Operation(summary = "添加物资")
public ApiResponse add(@RequestBody AddMatterDto addMatterDto) { public ApiResponse add(@RequestBody AddMatterDto addMatterDto) {
// 获取名称
String name = addMatterDto.getName();
// 判断名称是否存在
if (matterService.exists(new LambdaQueryWrapper<Matter>().eq(Matter::getName, name))) {
return ApiResponse.failure("物资已存在");
}
Matter matter = new Matter(); Matter matter = new Matter();
BeanUtils.copyProperties(addMatterDto, matter); BeanUtils.copyProperties(addMatterDto, matter);
if (matter.getNum() == null) {
matter.setNum(0);
}
matterService.save(matter); matterService.save(matter);
return ApiResponse.success(null); return ApiResponse.success(null);
} }
@ -61,7 +70,7 @@ public class MatterController {
@PostMapping("/list") @PostMapping("/list")
public ApiResponse list(@Parameter(description = "分页数量") @RequestParam(value = "pageNum") Integer pageNum, public ApiResponse list(@Parameter(description = "分页数量") @RequestParam(value = "pageNum") Integer pageNum,
@Parameter(description = "分页大小") @RequestParam(value = "pageSize") Integer pageSize, @Parameter(description = "分页大小") @RequestParam(value = "pageSize") Integer pageSize,
@Parameter(description = "物资名称") @RequestParam(value = "name") String name) { @Parameter(description = "物资名称") @RequestParam(value = "name", required = false) String name) {
LambdaQueryWrapper<Matter> queryWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<Matter> queryWrapper = new LambdaQueryWrapper<>();
if (StringUtils.isNotBlank(name)) { if (StringUtils.isNotBlank(name)) {
queryWrapper.like(Matter::getName, name); queryWrapper.like(Matter::getName, name);

View File

@ -42,7 +42,7 @@ import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Tag(name = "军标数据管理") @Tag(name = "军标数据管理")
@CheckAuth
@RestController @RestController
@RequestMapping("/militaryLibrary") @RequestMapping("/militaryLibrary")
public class MilitaryLibraryController { public class MilitaryLibraryController {

View File

@ -42,7 +42,7 @@ import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Tag(name = "模型数据管理") @Tag(name = "模型数据管理")
@CheckAuth
@RestController @RestController
@RequestMapping("/modelLibrary") @RequestMapping("/modelLibrary")
public class ModelLibraryController { public class ModelLibraryController {
@ -543,7 +543,7 @@ public class ModelLibraryController {
// 先将当前分类ID加入结果列表确保包含自身 // 先将当前分类ID加入结果列表确保包含自身
resultList.add(currentTypeId); resultList.add(currentTypeId);
// 查询当前分类的「直接子分类」(按 tree_index 排序、保持树形结构原有顺序) // 查询当前分类的「直接子分类」
String childSql = "SELECT id FROM model_type WHERE parent_id = ? ORDER BY tree_index ASC"; String childSql = "SELECT id FROM model_type WHERE parent_id = ? ORDER BY tree_index ASC";
List<Object> childParams = new ArrayList<>(); List<Object> childParams = new ArrayList<>();
childParams.add(currentTypeId); childParams.add(currentTypeId);
@ -578,5 +578,4 @@ public class ModelLibraryController {
} }
return str.startsWith(".") ? str.substring(1) : str; return str.startsWith(".") ? str.substring(1) : str;
} }
} }

View File

@ -5,15 +5,15 @@ import com.yj.earth.vo.PoiVo;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.sql.*;
import java.io.File; import java.io.File;
import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -21,15 +21,20 @@ import java.util.List;
@RestController @RestController
@RequestMapping("/poi") @RequestMapping("/poi")
public class PoiController { public class PoiController {
private static Connection connection; private static final Logger logger = LoggerFactory.getLogger(PoiController.class);
static { @Value("${poi.global.enabled:false}")
try { private boolean poiEnabled;
private Connection connection;
// 初始化数据库连接的方法
private void initConnection() throws SQLException, ClassNotFoundException {
if (connection == null || connection.isClosed()) {
Class.forName("org.sqlite.JDBC"); Class.forName("org.sqlite.JDBC");
String dbPath = System.getProperty("user.dir") + File.separator + "poi" + File.separator + "poi.db"; String dbPath = System.getProperty("user.dir") + File.separator + "poi" + File.separator + "poi.db";
connection = DriverManager.getConnection("jdbc:sqlite:" + dbPath); connection = DriverManager.getConnection("jdbc:sqlite:" + dbPath);
} catch (Exception e) { logger.info("POI数据库连接初始化成功路径{}", dbPath);
throw new RuntimeException("SQLite连接初始化失败", e);
} }
} }
@ -38,6 +43,16 @@ public class PoiController {
public ApiResponse data(@Parameter(description = "分页页码") Integer pageNum, public ApiResponse data(@Parameter(description = "分页页码") Integer pageNum,
@Parameter(description = "分页大小") Integer pageSize, @Parameter(description = "分页大小") Integer pageSize,
@Parameter(description = "名称搜索") String name) { @Parameter(description = "名称搜索") String name) {
// 检查功能是否开启
if (!poiEnabled) {
return ApiResponse.failure("全国POI搜索功能已关闭");
}
// 检查分页参数合法性
if (pageNum == null || pageSize == null || pageNum < 1 || pageSize < 1) {
return ApiResponse.failure("无效的分页参数");
}
int offset = (pageNum - 1) * pageSize; int offset = (pageNum - 1) * pageSize;
StringBuilder dataSql = new StringBuilder("SELECT id, name, lng, lat FROM data WHERE 1=1"); StringBuilder dataSql = new StringBuilder("SELECT id, name, lng, lat FROM data WHERE 1=1");
List<Object> params = new ArrayList<>(); List<Object> params = new ArrayList<>();
@ -51,8 +66,10 @@ public class PoiController {
// 添加分页条件 // 添加分页条件
dataSql.append(" LIMIT ? OFFSET ?"); dataSql.append(" LIMIT ? OFFSET ?");
try { try {
// 初始化连接(如果未初始化)
initConnection();
List<PoiVo> poiList = new ArrayList<>(); List<PoiVo> poiList = new ArrayList<>();
long dataStartTime = System.currentTimeMillis();
try (PreparedStatement dataPs = connection.prepareStatement(dataSql.toString())) { try (PreparedStatement dataPs = connection.prepareStatement(dataSql.toString())) {
int paramIndex = 1; int paramIndex = 1;
for (Object param : params) { for (Object param : params) {
@ -74,7 +91,11 @@ public class PoiController {
} }
return ApiResponse.success(poiList); return ApiResponse.success(poiList);
} catch (SQLException e) { } catch (SQLException e) {
logger.error("POI数据查询失败", e);
return ApiResponse.failure("POI数据查询失败" + e.getMessage()); return ApiResponse.failure("POI数据查询失败" + e.getMessage());
} catch (ClassNotFoundException e) {
logger.error("POI数据库驱动加载失败", e);
return ApiResponse.failure("POI功能初始化失败驱动未找到");
} }
} }
} }

View File

@ -30,7 +30,7 @@ import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Tag(name = "角色数据管理") @Tag(name = "角色数据管理")
@CheckAuth
@RestController @RestController
@RequestMapping("/role") @RequestMapping("/role")
public class RoleController { public class RoleController {

View File

@ -22,7 +22,7 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Tag(name = "角色资源管理") @Tag(name = "角色资源管理")
@CheckAuth
@RestController @RestController
@RequestMapping("/roleSource") @RequestMapping("/roleSource")
public class RoleSourceController { public class RoleSourceController {

View File

@ -36,7 +36,7 @@ import static com.yj.earth.common.constant.GlobalConstant.SHOW;
@Slf4j @Slf4j
@Tag(name = "树形结构管理") @Tag(name = "树形结构管理")
@CheckAuth
@RestController @RestController
@RequestMapping("/source") @RequestMapping("/source")
public class SourceController { public class SourceController {

View File

@ -177,7 +177,7 @@ public class SystemController {
source.setSourceType(resultSet.getString("source_type")); source.setSourceType(resultSet.getString("source_type"));
source.setSourcePath(resultSet.getString("source_path")); source.setSourcePath(resultSet.getString("source_path"));
// 关键修改读取原始parent_id而非覆盖为新父节点ID // 关键修改读取原始parent_id而非覆盖为新父节点ID
source.setParentId(resultSet.getString("parent_id")); source.setParentId(resultSet.getString("parent_id"));
Integer treeIndex = resultSet.getObject("tree_index") != null Integer treeIndex = resultSet.getObject("tree_index") != null

View File

@ -25,6 +25,8 @@ public class Matter implements Serializable {
private String name; private String name;
@Schema(description = "数量") @Schema(description = "数量")
private Integer num; private Integer num;
@Schema(description = "单位")
private String unit;
@Schema(description = "创建时间") @Schema(description = "创建时间")
@TableField(fill = FieldFill.INSERT) @TableField(fill = FieldFill.INSERT)
private LocalDateTime createdAt; private LocalDateTime createdAt;

View File

@ -1,6 +1,8 @@
package com.yj.earth.business.domain; package com.yj.earth.business.domain;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
@ -23,7 +25,9 @@ public class PoiInfo implements Serializable {
@Schema(description = "是否启用") @Schema(description = "是否启用")
private Integer isEnable; private Integer isEnable;
@Schema(description = "创建时间") @Schema(description = "创建时间")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createdAt; private LocalDateTime createdAt;
@Schema(description = "更新时间") @Schema(description = "更新时间")
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updatedAt; private LocalDateTime updatedAt;
} }

View File

@ -1,6 +1,7 @@
package com.yj.earth.business.service.impl; package com.yj.earth.business.service.impl;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.drew.imaging.ImageMetadataReader; import com.drew.imaging.ImageMetadataReader;
import com.drew.lang.Rational; import com.drew.lang.Rational;
import com.drew.metadata.Metadata; import com.drew.metadata.Metadata;
@ -8,14 +9,10 @@ import com.drew.metadata.exif.GpsDirectory;
import com.yj.earth.business.domain.FileInfo; import com.yj.earth.business.domain.FileInfo;
import com.yj.earth.business.mapper.FileInfoMapper; import com.yj.earth.business.mapper.FileInfoMapper;
import com.yj.earth.business.service.FileInfoService; import com.yj.earth.business.service.FileInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yj.earth.datasource.DatabaseManager; import com.yj.earth.datasource.DatabaseManager;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils; import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.File;

View File

@ -1,5 +1,6 @@
package com.yj.earth.common.config; package com.yj.earth.common.config;
import cn.dev33.satoken.exception.NotLoginException;
import com.yj.earth.common.exception.UnAuthException; import com.yj.earth.common.exception.UnAuthException;
import com.yj.earth.common.util.ApiResponse; import com.yj.earth.common.util.ApiResponse;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -9,14 +10,20 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j @Slf4j
@RestControllerAdvice @RestControllerAdvice
public class GlobalExceptionHandler { public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ApiResponse handleException(Exception e) {
return ApiResponse.failure(e.getMessage());
}
@ExceptionHandler(UnAuthException.class) @ExceptionHandler(UnAuthException.class)
public ApiResponse handleUnAuthException(UnAuthException e) { public ApiResponse handleUnAuthException(UnAuthException e) {
return ApiResponse.failureWithNoAuth(e.getMessage()); return ApiResponse.failureWithNoAuth(e.getMessage());
} }
@ExceptionHandler(NotLoginException.class)
public ApiResponse handleNotLoginException(NotLoginException e) {
return ApiResponse.failureWithNoAuth(e.getMessage());
}
@ExceptionHandler(Exception.class)
public ApiResponse handleException(Exception e) {
log.error("Exception: ", e);
return ApiResponse.failure(e.getMessage());
}
} }

View File

@ -131,7 +131,7 @@ public class PoiExporter {
} }
// 批量插入(带进度日志) // 批量插入(带进度日志)
int batchSize = 5000; int batchSize = 1000;
int totalCount = 0; // 总处理数据量 int totalCount = 0; // 总处理数据量
try (ResultSet rs = queryPs.executeQuery()) { try (ResultSet rs = queryPs.executeQuery()) {
while (rs.next()) { while (rs.next()) {
@ -165,7 +165,7 @@ public class PoiExporter {
public static void main(String[] args) { public static void main(String[] args) {
try { try {
new PoiExporter().exportPoiByArea("兰州"); new PoiExporter().exportPoiByArea("重庆");
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -3,11 +3,13 @@ package com.yj.earth.datasource;
import com.yj.earth.design.*; import com.yj.earth.design.*;
import lombok.Data; import lombok.Data;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import java.io.IOException; import javax.annotation.PostConstruct;
import java.io.InputStream; import java.io.*;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.file.Files; import java.nio.file.Files;
@ -21,14 +23,31 @@ import java.util.Map;
@Data @Data
@Slf4j @Slf4j
@Component
public class DatabaseManager { public class DatabaseManager {
public static String getRecommendedCacheDirectory() {
return FOLDER_NAME;
}
public enum DatabaseType { public enum DatabaseType {
SQLITE, MYSQL SQLITE, MYSQL
} }
@Value("${server.path}")
private String path;
private static String FOLDER_NAME;
private static boolean isPathInitialized = false;
@PostConstruct
public void init() {
FOLDER_NAME = this.path;
isPathInitialized = true;
log.info("数据库路径已初始化: {}", FOLDER_NAME);
}
private static final String EXCLUDE_SERIAL_FIELD = "serialVersionUID"; private static final String EXCLUDE_SERIAL_FIELD = "serialVersionUID";
private static final List<Class<?>> ENTITY_CLASSES; private static final List<Class<?>> ENTITY_CLASSES;
private static final String FOLDER_NAME = "yjearth";
private static final String DB_FILE_NAME = "app.db"; private static final String DB_FILE_NAME = "app.db";
private static String sqliteDbFilePath; private static String sqliteDbFilePath;
private static boolean isSqliteInitialized = false; private static boolean isSqliteInitialized = false;
@ -64,6 +83,15 @@ public class DatabaseManager {
ENTITY_CLASSES = Collections.unmodifiableList(classes); ENTITY_CLASSES = Collections.unmodifiableList(classes);
} }
// 新增方法:提前初始化路径
public static void initializePath(String path) {
if (!isPathInitialized) {
FOLDER_NAME = path;
isPathInitialized = true;
log.info("数据库路径已提前初始化: {}", FOLDER_NAME);
}
}
public static void initDatabase(DatabaseType dbType) { public static void initDatabase(DatabaseType dbType) {
if (dbType == null) { if (dbType == null) {
log.error("数据库类型不能为空"); log.error("数据库类型不能为空");
@ -112,6 +140,16 @@ public class DatabaseManager {
} }
public static String getSqliteDbFilePath() { public static String getSqliteDbFilePath() {
if (!isPathInitialized || FOLDER_NAME == null) {
throw new IllegalStateException("数据库路径尚未初始化,请先调用 initializePath 方法或等待 @PostConstruct 完成");
}
if (sqliteDbFilePath == null) {
// 如果没有预先创建,则动态构建路径
Path appDir = Paths.get(FOLDER_NAME);
Path dbFile = appDir.resolve(DB_FILE_NAME);
sqliteDbFilePath = dbFile.toAbsolutePath().toString();
}
return sqliteDbFilePath; return sqliteDbFilePath;
} }
@ -132,7 +170,13 @@ public class DatabaseManager {
} }
private static boolean validateConfig(DatabaseType dbType) { private static boolean validateConfig(DatabaseType dbType) {
if (dbType == DatabaseType.SQLITE) return true; if (dbType == DatabaseType.SQLITE) {
if (!isPathInitialized || FOLDER_NAME == null) {
log.error("SQLite配置缺失: server.path 尚未初始化");
return false;
}
return true;
}
if (mysqlUrl == null || mysqlUrl.isEmpty()) { if (mysqlUrl == null || mysqlUrl.isEmpty()) {
log.error("MySQL配置缺失: spring.datasource.mysql.url"); log.error("MySQL配置缺失: spring.datasource.mysql.url");
@ -162,31 +206,44 @@ public class DatabaseManager {
private static void preProcess(DatabaseType dbType) throws IOException { private static void preProcess(DatabaseType dbType) throws IOException {
if (dbType != DatabaseType.SQLITE) return; if (dbType != DatabaseType.SQLITE) return;
Path systemCacheDir = getRecommendedCacheDirectory(); // 直接使用配置的绝对路径
if (systemCacheDir == null) { if (FOLDER_NAME == null || FOLDER_NAME.trim().isEmpty()) {
throw new IOException("无法获取有效的系统缓存目录、无法创建SQLite文件"); throw new IOException("server.path 配置为空,无法创建SQLite数据库文件");
} }
Path appDir = systemCacheDir.resolve(FOLDER_NAME); Path appDir = Paths.get(FOLDER_NAME);
Path dbFile = appDir.resolve(DB_FILE_NAME); Path dbFile = appDir.resolve(DB_FILE_NAME);
sqliteDbFilePath = dbFile.toAbsolutePath().toString(); sqliteDbFilePath = dbFile.toAbsolutePath().toString();
// 创建目录(如果不存在)
if (!Files.exists(appDir)) { if (!Files.exists(appDir)) {
try {
Files.createDirectories(appDir); Files.createDirectories(appDir);
log.info("创建SQLite应用目录: {}", appDir); log.info("创建SQLite数据库目录: {}", appDir);
} catch (IOException e) {
throw new IOException("无法创建SQLite数据库目录: " + appDir + ", 错误: " + e.getMessage(), e);
} }
}
// 检查目录写入权限
if (!Files.isWritable(appDir)) { if (!Files.isWritable(appDir)) {
throw new IOException("无权限写入SQLite目录: " + appDir); throw new IOException("无权限写入SQLite目录: " + appDir);
} }
// 创建数据库文件(如果不存在)
if (!Files.exists(dbFile)) { if (!Files.exists(dbFile)) {
try {
Files.createFile(dbFile); Files.createFile(dbFile);
log.info("创建SQLite文件: {}", sqliteDbFilePath); log.info("创建SQLite数据库文件: {}", sqliteDbFilePath);
} catch (IOException e) {
throw new IOException("无法创建SQLite数据库文件: " + dbFile + ", 错误: " + e.getMessage(), e);
}
} else { } else {
log.info("SQLite文件已存在: {}", sqliteDbFilePath); log.info("SQLite数据库文件已存在: {}", sqliteDbFilePath);
} }
} }
// ... 其他方法保持不变 ...
private static void createTablesForEntities(DatabaseType dbType) throws SQLException { private static void createTablesForEntities(DatabaseType dbType) throws SQLException {
if (ENTITY_CLASSES.isEmpty()) { if (ENTITY_CLASSES.isEmpty()) {
log.warn("未配置需要创建表的实体类、跳过批量建表"); log.warn("未配置需要创建表的实体类、跳过批量建表");
@ -300,35 +357,6 @@ public class DatabaseManager {
} }
} }
public static Path getRecommendedCacheDirectory() {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
String appData = System.getenv("APPDATA");
if (appData != null && !appData.isEmpty()) {
Path path = Paths.get(appData);
if (Files.exists(path) && Files.isWritable(path)) {
return path;
}
}
} else if (os.contains("nix") || os.contains("nux")) {
String userHome = System.getProperty("user.home");
if (userHome != null && !userHome.isEmpty()) {
Path path = Paths.get(userHome).resolve(".cache");
try {
if (!Files.exists(path)) {
Files.createDirectories(path);
}
if (Files.isWritable(path)) {
return path;
}
} catch (IOException e) {
log.error("无法访问Linux .cache目录: {}", e.getMessage(), e);
}
}
}
return null;
}
private static String mapJavaTypeToMysql(Class<?> javaType) { private static String mapJavaTypeToMysql(Class<?> javaType) {
if (javaType == int.class || javaType == Integer.class) { if (javaType == int.class || javaType == Integer.class) {
return "INT"; return "INT";
@ -411,4 +439,55 @@ public class DatabaseManager {
} }
return "sqlite"; return "sqlite";
} }
private static String readServerPathFromConfig() {
// 先尝试读取外部配置JAR同级或项目根目录
String externalConfigPath = System.getProperty("user.dir") + File.separator + "application.yml";
File externalConfigFile = new File(externalConfigPath);
if (externalConfigFile.exists() && externalConfigFile.isFile()) {
try (InputStream input = new FileInputStream(externalConfigFile)) {
return parseServerPath(input);
} catch (Exception e) {
log.error("读取外部配置文件失败: {}", e.getMessage());
}
}
// 外部配置不存在、读取类路径内部配置
try (InputStream input = new ClassPathResource("application.yml").getInputStream()) {
return parseServerPath(input);
} catch (Exception e) {
log.error("读取内部配置文件失败: {}", e.getMessage());
}
return null;
}
// 从输入流中解析 server.path
private static String parseServerPath(InputStream input) {
Yaml yaml = new Yaml();
Map<String, Object> yamlData = yaml.load(input);
if (yamlData.containsKey("server") && yamlData.get("server") instanceof Map) {
Map<String, Object> serverMap = (Map<String, Object>) yamlData.get("server");
Object pathObj = serverMap.get("path");
return pathObj != null ? pathObj.toString().trim() : null;
}
return null;
}
/**
* 提前初始化数据库路径
*/
public static void initializeDatabasePath() {
try {
String serverPath = readServerPathFromConfig();
if (serverPath != null && !serverPath.trim().isEmpty()) {
DatabaseManager.initializePath(serverPath);
log.info("已提前初始化数据库路径: {}", serverPath);
} else {
log.warn("未找到 server.path 配置,将等待 @PostConstruct 初始化");
}
} catch (Exception e) {
log.warn("提前初始化数据库路径失败,将等待 @PostConstruct 初始化: {}", e.getMessage());
}
}
} }

View File

@ -13,6 +13,8 @@ public class Matter {
private String name; private String name;
@Schema(description = "数量") @Schema(description = "数量")
private Integer num; private Integer num;
@Schema(description = "单位")
private String unit;
@Schema(description = "创建时间") @Schema(description = "创建时间")
private LocalDateTime createdAt; private LocalDateTime createdAt;
@Schema(description = "更新时间") @Schema(description = "更新时间")

View File

@ -9,4 +9,6 @@ public class AddMatterDto {
private String name; private String name;
@Schema(description = "数量") @Schema(description = "数量")
private Integer num; private Integer num;
@Schema(description = "单位")
private String unit;
} }

View File

@ -11,4 +11,6 @@ public class UpdateMatterDto {
private String name; private String name;
@Schema(description = "数量") @Schema(description = "数量")
private Integer num; private Integer num;
@Schema(description = "单位")
private String unit;
} }

View File

@ -1,10 +1,15 @@
server: server:
host: 127.0.0.1 host: 127.0.0.1
port: 8848 port: 8848
path: C:\abcdefghijklmnopqrstuvwxyz
sdk: sdk:
port: 8888 port: 8888
poi:
global:
enabled: false
spring: spring:
main: main:
banner-mode: off banner-mode: off
@ -16,6 +21,7 @@ spring:
url: jdbc:mysql://192.168.110.65:6975/yjearth?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 url: jdbc:mysql://192.168.110.65:6975/yjearth?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: yjearth username: yjearth
password: kNGxrsSSYMexZ2t4 password: kNGxrsSSYMexZ2t4
servlet: servlet:
multipart: multipart:
max-file-size: 1024MB max-file-size: 1024MB