diff --git a/nex-be/src/main/java/com/unisinsight/project/controller/DeviceController.java b/nex-be/src/main/java/com/unisinsight/project/controller/DeviceController.java index a3d8e3f..35d67ff 100644 --- a/nex-be/src/main/java/com/unisinsight/project/controller/DeviceController.java +++ b/nex-be/src/main/java/com/unisinsight/project/controller/DeviceController.java @@ -52,6 +52,15 @@ public class DeviceController { log.info("终端修改请求参数为:{}", JSONUtil.toJsonStr(deviceReq)); return deviceService.update(deviceReq); } + @ApiOperation(value = "终端查询") + @PostMapping("/query") + public Result queryUser(@RequestBody DeviceReq deviceReq) { + if (Objects.isNull(deviceReq)) { + return Result.errorResult(BaseErrorCode.PARAMS_CHK_ERROR); + } + log.info("终端查询请求参数为:{}", JSONUtil.toJsonStr(deviceReq)); + return deviceService.query(deviceReq); + } @ApiOperation(value = "终端删除") @PostMapping("/delete") diff --git a/nex-be/src/main/java/com/unisinsight/project/controller/DeviceUserMappingController.java b/nex-be/src/main/java/com/unisinsight/project/controller/DeviceUserMappingController.java index ee35435..d547330 100644 --- a/nex-be/src/main/java/com/unisinsight/project/controller/DeviceUserMappingController.java +++ b/nex-be/src/main/java/com/unisinsight/project/controller/DeviceUserMappingController.java @@ -2,9 +2,7 @@ package com.unisinsight.project.controller; import cn.hutool.json.JSONUtil; import com.unisinsight.project.entity.req.DeviceUserMappingReq; -import com.unisinsight.project.entity.req.DeviceUserReq; import com.unisinsight.project.entity.res.DeviceUserMappingRes; -import com.unisinsight.project.entity.res.ImageRes; import com.unisinsight.project.exception.BaseErrorCode; import com.unisinsight.project.exception.Result; import com.unisinsight.project.service.DeviceUserMappingService; @@ -54,14 +52,6 @@ public class DeviceUserMappingController { return deviceUserMappingService.select(deviceUserMappingReq); } - @ApiOperation(value = "用户登录") - @PostMapping("/login") - public Result> loginUser(@RequestBody DeviceUserReq deviceUserReq) { - if (Objects.isNull(deviceUserReq)) { - return Result.errorResult(BaseErrorCode.PARAMS_CHK_ERROR); - } - log.info("用户登录请求参数为:{}", JSONUtil.toJsonStr(deviceUserReq)); - return deviceUserMappingService.loginUser(deviceUserReq); - } + } diff --git a/nex-be/src/main/java/com/unisinsight/project/controller/FileChunkController.java b/nex-be/src/main/java/com/unisinsight/project/controller/FileChunkController.java index 12e31c4..5b16cdd 100644 --- a/nex-be/src/main/java/com/unisinsight/project/controller/FileChunkController.java +++ b/nex-be/src/main/java/com/unisinsight/project/controller/FileChunkController.java @@ -1,11 +1,17 @@ package com.unisinsight.project.controller; +import com.unisinsight.project.entity.dao.Image; +import com.unisinsight.project.mapper.ImageMapper; +import com.unisinsight.project.util.DigestUtil; import io.swagger.annotations.*; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; +import javax.annotation.Resource; import java.io.File; import java.io.IOException; import java.io.OutputStream; @@ -24,39 +30,45 @@ import java.util.concurrent.ConcurrentHashMap; @RestController @RequestMapping("/api/files") @Api(tags = "文件分片上传接口") +@Slf4j public class FileChunkController { // 临时目录,用于存储上传的分片 - @Value("${file.upload.temp-dir:${file.upload.temp-dir}/chunked-uploads}") + @Value("${file.upload.temp-dir:${java.io.tmpdir}/chunked-uploads}") private String tempDir; // 最终文件存储目录 - @Value("${file.upload.dir:${file.upload.dir}/uploads}") + @Value("${file.upload.dir:${user.home}/uploads}") private String uploadDir; // 存储每个文件的分片信息 private final Map fileUploadMap = new ConcurrentHashMap<>(); + @Resource + private ImageMapper imageMapper; + /** * 上传文件分片 - * - * @param chunk 分片文件 - * @param fileId 文件唯一标识符 + * + * @param chunk 分片文件 + * @param fileId 文件唯一标识符 * @param chunkNumber 当前分片编号(从1开始) * @param totalChunks 总分片数 - * @param fileName 原始文件名 - * @param totalSize 文件总大小 + * @param fileName 原始文件名 + * @param totalSize 文件总大小 * @return 上传结果 */ @PostMapping("/upload-chunk") @ApiOperation(value = "上传文件分片", notes = "上传单个文件分片,当所有分片上传完成后自动合并文件") @ApiImplicitParams({ @ApiImplicitParam(name = "chunk", value = "文件分片", required = true, dataType = "__File", paramType = "form"), - @ApiImplicitParam(name = "fileId", value = "文件唯一标识符", required = true, dataType = "String", paramType = "query"), - @ApiImplicitParam(name = "chunkNumber", value = "当前分片编号(从1开始)", required = true, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = "totalChunks", value = "总分片数", required = true, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = "fileName", value = "原始文件名", required = true, dataType = "String", paramType = "query"), - @ApiImplicitParam(name = "totalSize", value = "文件总大小", required = true, dataType = "long", paramType = "query") + @ApiImplicitParam(name = "chunk_size", value = "文件分片大小", required = true, dataType = "int", paramType = "query"), + @ApiImplicitParam(name = "chunk_md5", value = "文件分片md5", required = true, dataType = "String", paramType = "query"), + @ApiImplicitParam(name = "file_id", value = "文件唯一标识符", required = true, dataType = "String", paramType = "query"), + @ApiImplicitParam(name = "shard_index", value = "当前分片编号(从1开始)", required = true, dataType = "int", paramType = "query"), + @ApiImplicitParam(name = "shard_total", value = "总分片数", required = true, dataType = "int", paramType = "query"), + @ApiImplicitParam(name = "file_name", value = "原始文件名", required = true, dataType = "String", paramType = "query"), + @ApiImplicitParam(name = "file_size", value = "文件总大小", required = true, dataType = "long", paramType = "query") }) @ApiResponses({ @ApiResponse(code = 200, message = "上传成功"), @@ -64,31 +76,40 @@ public class FileChunkController { }) public ResponseEntity> uploadChunk( @RequestParam("chunk") MultipartFile chunk, - @RequestParam("fileId") String fileId, - @RequestParam("chunkNumber") int chunkNumber, - @RequestParam("totalChunks") int totalChunks, - @RequestParam("fileName") String fileName, - @RequestParam("totalSize") long totalSize) { - + @RequestParam("chunk_size") int chunkSize, + @RequestParam("chunk_md5") String chunkMd5, + @RequestParam("file_id") String fileId, + @RequestParam("shard_index") int chunkNumber, + @RequestParam("shard_total") int totalChunks, + @RequestParam("file_name") String fileName, + @RequestParam("file_size") long totalSize) { + Map response = new HashMap<>(); - + try { + String md5 = DigestUtil.encryptMd5(chunk.getBytes()); + if (!chunkMd5.equals(md5)) { + log.info("分片文件md5校验失败,chunkMd5:{},md5:{}", chunkMd5, md5); + throw new RuntimeException("分片文件md5校验失败"); + } // 创建临时目录 Path fileTempDir = Paths.get(tempDir, fileId); if (!Files.exists(fileTempDir)) { Files.createDirectories(fileTempDir); } - + log.info("创建临时目录: {}", fileTempDir); + log.info("上传分片文件: {}", fileName); // 保存分片文件 String chunkFileName = String.format("%05d.part", chunkNumber); + log.info("保存分片文件: {}", chunkFileName); Path chunkFilePath = fileTempDir.resolve(chunkFileName); chunk.transferTo(chunkFilePath); // 更新文件上传信息 - FileUploadInfo uploadInfo = fileUploadMap.computeIfAbsent(fileId, - id -> new FileUploadInfo(id, fileName, totalChunks, totalSize)); + FileUploadInfo uploadInfo = fileUploadMap.computeIfAbsent(fileId, + id -> new FileUploadInfo(id, fileName, totalChunks, totalSize)); uploadInfo.addUploadedChunk(chunkNumber); - +// log.info("更新文件上传信息: {}", JSONUtil.toJsonStr(uploadInfo)); // 检查是否所有分片都已上传 if (uploadInfo.isUploadComplete()) { // 合并文件 @@ -96,19 +117,32 @@ public class FileChunkController { if (!Files.exists(finalDir)) { Files.createDirectories(finalDir); } - + log.info("合并文件: {}", finalDir); Path finalFilePath = finalDir.resolve(fileName); + log.info("合并所有分片文件: {}", finalFilePath.getFileName()); mergeChunks(fileId, finalFilePath, totalChunks); // 清理临时文件 + log.info("清理临时文件: {}", fileId); cleanupTempFiles(fileId); - + // 从上传映射中移除 fileUploadMap.remove(fileId); - response.put("status", "completed"); - response.put("message", "文件上传并合并完成"); - response.put("filePath", finalFilePath.toString()); + Image image = new Image(); + image.setImageName(fileName); + image.setStoragePath(uploadDir); + image.setImageStatus(1); + int insert = imageMapper.insert(image); + log.info("镜像新增insert:{}", insert); + if (insert == 1) { + response.put("status", "completed"); + response.put("message", "文件上传并合并完成"); + response.put("filePath", finalFilePath.toString()); + } else { + throw new RuntimeException("文件上传失败"); + } + } else { response.put("status", "uploading"); response.put("message", "分片上传成功"); @@ -121,14 +155,22 @@ public class FileChunkController { } catch (Exception e) { response.put("success", false); + response.put("status", "error"); response.put("message", "上传失败: " + e.getMessage()); + log.info("上次失败清理临时文件: {}", fileId); + try { + cleanupTempFiles(fileId); + cleanUploadFile(fileName); + } catch (IOException ex) { + log.error("清理临时文件失败,fileId:{}, {}", fileId, ex.getMessage(), ex); + } return ResponseEntity.status(500).body(response); } } /** * 查询文件上传状态 - * + * * @param fileId 文件唯一标识符 * @return 上传状态信息 */ @@ -136,7 +178,7 @@ public class FileChunkController { @ApiOperation("查询文件上传状态") public ResponseEntity> getUploadStatus(@PathVariable String fileId) { Map response = new HashMap<>(); - + FileUploadInfo uploadInfo = fileUploadMap.get(fileId); if (uploadInfo == null) { // 检查文件是否已经完成上传并合并 @@ -160,32 +202,32 @@ public class FileChunkController { response.put("totalChunks", uploadInfo.getTotalChunks()); response.put("progress", (double) uploadInfo.getUploadedChunks().size() / uploadInfo.getTotalChunks()); } - + response.put("success", true); return ResponseEntity.ok(response); } /** * 合并所有分片文件 - * - * @param fileId 文件唯一标识符 - * @param outputPath 合并后的文件路径 + * + * @param fileId 文件唯一标识符 + * @param outputPath 合并后的文件路径 * @param totalChunks 总分片数 * @throws IOException IO异常 */ private void mergeChunks(String fileId, Path outputPath, int totalChunks) throws IOException { try (OutputStream outputStream = Files.newOutputStream(outputPath)) { Path fileTempDir = Paths.get(tempDir, fileId); - + // 按顺序合并分片 for (int i = 1; i <= totalChunks; i++) { String chunkFileName = String.format("%05d.part", i); Path chunkPath = fileTempDir.resolve(chunkFileName); - + if (!Files.exists(chunkPath)) { throw new IOException("缺少分片文件: " + chunkFileName); } - + // 将分片内容追加到输出文件 Files.copy(chunkPath, outputStream); } @@ -194,7 +236,7 @@ public class FileChunkController { /** * 清理临时分片文件 - * + * * @param fileId 文件唯一标识符 * @throws IOException IO异常 */ @@ -203,15 +245,34 @@ public class FileChunkController { if (Files.exists(fileTempDir)) { // 递归删除临时目录及其内容 Files.walk(fileTempDir) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); } } + /** + * 根据文件名删除已上传的文件 + * + * @param fileName 文件名 + * @throws IOException IO异常 + */ + private void cleanUploadFile(String fileName) throws IOException { + Path filePath = Paths.get(uploadDir, fileName); + if (Files.exists(filePath)) { + // 删除文件 + Files.delete(filePath); + log.info("已删除文件: {}", filePath); + } else { + log.warn("文件不存在,无需删除: {}", filePath); + } + } + + /** * 文件上传信息类 */ + @Data private static class FileUploadInfo { private final String fileId; private final String fileName; @@ -235,30 +296,6 @@ public class FileChunkController { return uploadedChunks.size() == totalChunks; } - public String getFileId() { - return fileId; - } - - public String getFileName() { - return fileName; - } - - public int getTotalChunks() { - return totalChunks; - } - - public long getTotalSize() { - return totalSize; - } - - public Set getUploadedChunks() { - return uploadedChunks; - } } - @GetMapping("/test") - @ApiOperation("测试") - public ResponseEntity getUploadStatus() { - return ResponseEntity.ok("ok"); - } } diff --git a/nex-be/src/main/java/com/unisinsight/project/controller/ImageController.java b/nex-be/src/main/java/com/unisinsight/project/controller/ImageController.java index 32c6b2c..c79a50c 100644 --- a/nex-be/src/main/java/com/unisinsight/project/controller/ImageController.java +++ b/nex-be/src/main/java/com/unisinsight/project/controller/ImageController.java @@ -1,6 +1,7 @@ package com.unisinsight.project.controller; import cn.hutool.json.JSONUtil; +import com.unisinsight.project.entity.req.DeleteIdReq; import com.unisinsight.project.entity.req.ImageReq; import com.unisinsight.project.entity.res.ImageRes; import com.unisinsight.project.entity.res.PageResult; @@ -42,4 +43,15 @@ public class ImageController { return imageService.selectPage(imageReq); } + @ApiOperation(value = "镜像删除") + @PostMapping("/delete") + public Result deleteUser(@RequestBody DeleteIdReq deleteIdReq) { + if (Objects.isNull(deleteIdReq)) { + return Result.errorResult(BaseErrorCode.PARAMS_CHK_ERROR); + } + log.info("镜像删除请求参数为:{}", JSONUtil.toJsonStr(deleteIdReq)); + return imageService.delete(deleteIdReq); + } + + } diff --git a/nex-be/src/main/java/com/unisinsight/project/controller/UserController.java b/nex-be/src/main/java/com/unisinsight/project/controller/UserController.java index 8c8f88e..4d2ca62 100644 --- a/nex-be/src/main/java/com/unisinsight/project/controller/UserController.java +++ b/nex-be/src/main/java/com/unisinsight/project/controller/UserController.java @@ -2,21 +2,22 @@ package com.unisinsight.project.controller; import cn.hutool.json.JSONUtil; import com.unisinsight.project.entity.req.DeleteIdReq; +import com.unisinsight.project.entity.req.DeviceUserReq; import com.unisinsight.project.entity.req.UserReq; +import com.unisinsight.project.entity.res.ImageRes; import com.unisinsight.project.entity.res.PageResult; import com.unisinsight.project.entity.res.UserRes; import com.unisinsight.project.exception.BaseErrorCode; import com.unisinsight.project.exception.Result; +import com.unisinsight.project.service.DeviceUserMappingService; import com.unisinsight.project.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; +import java.util.List; import java.util.Objects; /** @@ -34,6 +35,9 @@ public class UserController { @Resource private UserService userService; + @Resource + private DeviceUserMappingService deviceUserMappingService; + @ApiOperation(value = "用户新增") @PostMapping("/add") public Result insertUser(@RequestBody UserReq userReq) { @@ -54,6 +58,16 @@ public class UserController { return userService.update(userReq); } + @ApiOperation(value = "用户查询") + @PostMapping("/query") + public Result queryUser(@RequestBody UserReq userReq) { + if (Objects.isNull(userReq)) { + return Result.errorResult(BaseErrorCode.PARAMS_CHK_ERROR); + } + log.info("用户查询请求参数为:{}", JSONUtil.toJsonStr(userReq)); + return userService.query(userReq); + } + @ApiOperation(value = "用户删除") @PostMapping("/delete") public Result deleteUser(@RequestBody DeleteIdReq deleteIdReq) { @@ -74,5 +88,30 @@ public class UserController { return userService.selectPageUser(userReq); } + @ApiOperation(value = "用户认证") + @PostMapping("/auth") + public Result> authentication(@RequestParam("deviceId") String deviceId) { + if (Objects.isNull(deviceId)) { + return Result.errorResult(BaseErrorCode.PARAMS_CHK_ERROR); + } + log.info("用户认证请求参数为:{}", deviceId); + return Result.successResult(); + } + + @ApiOperation(value = "用户登录") + @PostMapping("/login") + public Result loginUser(@RequestParam("deviceId") String deviceId, + @RequestParam("username") String username, + @RequestParam("password") String password) { + if (Objects.isNull(deviceId) || Objects.isNull(username) || Objects.isNull(password)) { + return Result.errorResult(BaseErrorCode.PARAMS_CHK_ERROR); + } + log.info("用户登录请求参数为,deviceId:{},username:{},password:{}", deviceId, username, password); + DeviceUserReq deviceUserReq = new DeviceUserReq(); + deviceUserReq.setDeviceId(deviceId); + deviceUserReq.setUserName(username); + deviceUserReq.setPassword(password); + return deviceUserMappingService.loginUser(deviceUserReq); + } } diff --git a/nex-be/src/main/java/com/unisinsight/project/entity/dao/Image.java b/nex-be/src/main/java/com/unisinsight/project/entity/dao/Image.java index db0cbf0..2a5fa28 100644 --- a/nex-be/src/main/java/com/unisinsight/project/entity/dao/Image.java +++ b/nex-be/src/main/java/com/unisinsight/project/entity/dao/Image.java @@ -32,7 +32,7 @@ public class Image implements Serializable { private Integer imageType; /** - * 镜像状态 + * 镜像状态: 1-成功,2-失败 */ @TableField(value = "image_status") private Integer imageStatus; diff --git a/nex-be/src/main/java/com/unisinsight/project/entity/req/DeleteIdReq.java b/nex-be/src/main/java/com/unisinsight/project/entity/req/DeleteIdReq.java index 27d557d..56c3688 100644 --- a/nex-be/src/main/java/com/unisinsight/project/entity/req/DeleteIdReq.java +++ b/nex-be/src/main/java/com/unisinsight/project/entity/req/DeleteIdReq.java @@ -13,6 +13,6 @@ import lombok.Data; @Data public class DeleteIdReq { - @ApiModelProperty(value = "id", dataType = "Long") - public Long id; + @ApiModelProperty(value = "id") + private Long id; } diff --git a/nex-be/src/main/java/com/unisinsight/project/entity/req/DeviceUserReq.java b/nex-be/src/main/java/com/unisinsight/project/entity/req/DeviceUserReq.java index 8588c82..7691645 100644 --- a/nex-be/src/main/java/com/unisinsight/project/entity/req/DeviceUserReq.java +++ b/nex-be/src/main/java/com/unisinsight/project/entity/req/DeviceUserReq.java @@ -24,7 +24,7 @@ public class DeviceUserReq { /** * 用户名 */ - @ApiModelProperty(value = "用户名", dataType = "String") + @ApiModelProperty(value = "用户名") @JsonProperty("user_name") private String userName; @@ -32,7 +32,7 @@ public class DeviceUserReq { /** * 密码 */ - @ApiModelProperty(value = "密码", dataType = "String") + @ApiModelProperty(value = "密码") @JsonProperty("password") private String password; diff --git a/nex-be/src/main/java/com/unisinsight/project/entity/req/ImageReq.java b/nex-be/src/main/java/com/unisinsight/project/entity/req/ImageReq.java index e3f19db..9b2240a 100644 --- a/nex-be/src/main/java/com/unisinsight/project/entity/req/ImageReq.java +++ b/nex-be/src/main/java/com/unisinsight/project/entity/req/ImageReq.java @@ -37,9 +37,9 @@ public class ImageReq implements Serializable { private Integer imageType; /** - * 镜像状态 + * 镜像状态: 1-成功,2-失败 */ - @ApiModelProperty("镜像状态") + @ApiModelProperty("镜像状态: 1-成功, 2-失败") @JsonProperty("image_status") private Integer imageStatus; @@ -75,7 +75,7 @@ public class ImageReq implements Serializable { /** * 查询页 */ - @ApiModelProperty(value = "查询页", notes = "分页查询时再传", dataType = "Integer") + @ApiModelProperty(value = "查询页", notes = "分页查询时再传") @JsonProperty("page_num") private Integer pageNum; @@ -83,7 +83,7 @@ public class ImageReq implements Serializable { /** * 每页数量 */ - @ApiModelProperty(value = "每页数量", notes = "分页查询时再传", dataType = "Integer") + @ApiModelProperty(value = "每页数量", notes = "分页查询时再传") @JsonProperty("page_size") private Integer pageSize; diff --git a/nex-be/src/main/java/com/unisinsight/project/entity/req/UserDeviceGroupReq.java b/nex-be/src/main/java/com/unisinsight/project/entity/req/UserDeviceGroupReq.java index 011d020..609f360 100644 --- a/nex-be/src/main/java/com/unisinsight/project/entity/req/UserDeviceGroupReq.java +++ b/nex-be/src/main/java/com/unisinsight/project/entity/req/UserDeviceGroupReq.java @@ -55,14 +55,14 @@ public class UserDeviceGroupReq implements Serializable { /** * 查询页 */ - @ApiModelProperty(value = "查询页", notes = "分页查询时再传", dataType = "Integer") + @ApiModelProperty(value = "查询页", notes = "分页查询时再传") @JsonProperty("page_num") private Integer pageNum; /** * 每页数量 */ - @ApiModelProperty(value = "每页数量", notes = "分页查询时再传", dataType = "Integer") + @ApiModelProperty(value = "每页数量", notes = "分页查询时再传") @JsonProperty("page_size") private Integer pageSize; diff --git a/nex-be/src/main/java/com/unisinsight/project/entity/req/UserReq.java b/nex-be/src/main/java/com/unisinsight/project/entity/req/UserReq.java index bfa6fd0..28b2747 100644 --- a/nex-be/src/main/java/com/unisinsight/project/entity/req/UserReq.java +++ b/nex-be/src/main/java/com/unisinsight/project/entity/req/UserReq.java @@ -113,7 +113,7 @@ public class UserReq implements Serializable { /** * 查询页 */ - @ApiModelProperty(value = "查询页", notes = "分页查询时再传", dataType = "Integer") + @ApiModelProperty(value = "查询页", notes = "分页查询时再传") @JsonProperty("page_num") private Integer pageNum; @@ -121,7 +121,7 @@ public class UserReq implements Serializable { /** * 每页数量 */ - @ApiModelProperty(value = "每页数量", notes = "分页查询时再传", dataType = "Integer") + @ApiModelProperty(value = "每页数量", notes = "分页查询时再传") @JsonProperty("page_size") private Integer pageSize; diff --git a/nex-be/src/main/java/com/unisinsight/project/entity/res/ImageRes.java b/nex-be/src/main/java/com/unisinsight/project/entity/res/ImageRes.java index db04905..eb5a2aa 100644 --- a/nex-be/src/main/java/com/unisinsight/project/entity/res/ImageRes.java +++ b/nex-be/src/main/java/com/unisinsight/project/entity/res/ImageRes.java @@ -39,7 +39,7 @@ public class ImageRes implements Serializable { /** * 镜像状态 */ - @ApiModelProperty("镜像状态") + @ApiModelProperty("镜像状态: 1-成功, 2-失败") @JsonProperty("image_status") private Integer imageStatus; diff --git a/nex-be/src/main/java/com/unisinsight/project/entity/res/PageResult.java b/nex-be/src/main/java/com/unisinsight/project/entity/res/PageResult.java index 5c9accb..3c382bd 100644 --- a/nex-be/src/main/java/com/unisinsight/project/entity/res/PageResult.java +++ b/nex-be/src/main/java/com/unisinsight/project/entity/res/PageResult.java @@ -3,6 +3,7 @@ package com.unisinsight.project.entity.res; import cn.hutool.core.bean.BeanUtil; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @@ -19,40 +20,42 @@ import java.util.List; public class PageResult { // 当前页码 @ApiModelProperty("当前页码") - private long current; + @JsonProperty("page_num") + private long pageNum; // 每页记录数 - @ApiModelProperty("每页记录数") - private long size; + @ApiModelProperty("每页条数") + @JsonProperty("page_size") + private long pageSize; // 总记录数 - @ApiModelProperty("总记录数") + @ApiModelProperty("总条数") private long total; // 总页数 @ApiModelProperty("总页数") private long pages; // 数据列表 @ApiModelProperty("数据列表") - private List records; + private List data; // 转换方法 public static PageResult convertIPage(IPage page, Class clazz) { PageResult result = new PageResult<>(); - result.setCurrent(page.getCurrent()); - result.setSize(page.getSize()); + result.setPageNum(page.getCurrent()); + result.setPageSize(page.getSize()); result.setTotal(page.getTotal()); result.setPages(page.getPages()); List copyToList = BeanUtil.copyToList(page.getRecords(), clazz); - result.setRecords(copyToList); + result.setData(copyToList); return result; } public static PageResult convertPage(Page page, Class clazz) { PageResult result = new PageResult<>(); - result.setCurrent(page.getCurrent()); - result.setSize(page.getSize()); + result.setPageNum(page.getCurrent()); + result.setPageSize(page.getSize()); result.setTotal(page.getTotal()); result.setPages(page.getPages()); List copyToList = BeanUtil.copyToList(page.getRecords(), clazz); - result.setRecords(copyToList); + result.setData(copyToList); return result; } } \ No newline at end of file diff --git a/nex-be/src/main/java/com/unisinsight/project/entity/res/UserRes.java b/nex-be/src/main/java/com/unisinsight/project/entity/res/UserRes.java index a24f291..01ab182 100644 --- a/nex-be/src/main/java/com/unisinsight/project/entity/res/UserRes.java +++ b/nex-be/src/main/java/com/unisinsight/project/entity/res/UserRes.java @@ -16,7 +16,7 @@ public class UserRes implements Serializable { /** * ID */ - @ApiModelProperty(value = "ID", dataType = "Long") + @ApiModelProperty(value = "ID") @JsonProperty("id") private Long id; @@ -24,7 +24,7 @@ public class UserRes implements Serializable { /** * 用户组ID */ - @ApiModelProperty(value = "用户组ID", dataType = "Long") + @ApiModelProperty(value = "用户组ID") @JsonProperty("user_group_id") private Long userGroupId; @@ -32,7 +32,7 @@ public class UserRes implements Serializable { /** * 用户名 */ - @ApiModelProperty(value = "用户名", dataType = "String") + @ApiModelProperty(value = "用户名") @JsonProperty("user_name") private String userName; @@ -40,7 +40,7 @@ public class UserRes implements Serializable { /** * 密码 */ - @ApiModelProperty(value = "密码", dataType = "String") + @ApiModelProperty(value = "密码") @JsonProperty("password") private String password; @@ -48,7 +48,7 @@ public class UserRes implements Serializable { /** * 生日 */ - @ApiModelProperty(value = "生日", dataType = "String") + @ApiModelProperty(value = "生日") @JsonProperty("birthday") private String birthday; @@ -56,7 +56,7 @@ public class UserRes implements Serializable { /** * 电话 */ - @ApiModelProperty(value = "电话", dataType = "String") + @ApiModelProperty(value = "电话") @JsonProperty("cell_phone") private String cellPhone; @@ -64,7 +64,7 @@ public class UserRes implements Serializable { /** * 邮箱 */ - @ApiModelProperty(value = "邮箱", dataType = "String") + @ApiModelProperty(value = "邮箱") @JsonProperty("email") private String email; @@ -73,7 +73,7 @@ public class UserRes implements Serializable { * 性别 */ - @ApiModelProperty(value = "性别", dataType = "Integer") + @ApiModelProperty(value = "性别") @JsonProperty("gender") private Integer gender; @@ -81,7 +81,7 @@ public class UserRes implements Serializable { /** * 身份证 */ - @ApiModelProperty(value = "身份证", dataType = "String") + @ApiModelProperty(value = "身份证") @JsonProperty("identity_no") private String identityNo; @@ -89,7 +89,7 @@ public class UserRes implements Serializable { /** * 优先级 */ - @ApiModelProperty(value = "优先级", dataType = "Integer") + @ApiModelProperty(value = "优先级") @JsonProperty("priority") private Integer priority; @@ -97,7 +97,7 @@ public class UserRes implements Serializable { /** * 用户类型 */ - @ApiModelProperty(value = "用户类型", dataType = "Integer") + @ApiModelProperty(value = "用户类型") @JsonProperty("user_type") private Integer userType; @@ -105,7 +105,7 @@ public class UserRes implements Serializable { /** * 状态 */ - @ApiModelProperty(value = "状态", dataType = "Integer") + @ApiModelProperty(value = "状态") @JsonProperty("status") private Integer status; diff --git a/nex-be/src/main/java/com/unisinsight/project/exception/BaseErrorCode.java b/nex-be/src/main/java/com/unisinsight/project/exception/BaseErrorCode.java index 3da804e..76a2b65 100644 --- a/nex-be/src/main/java/com/unisinsight/project/exception/BaseErrorCode.java +++ b/nex-be/src/main/java/com/unisinsight/project/exception/BaseErrorCode.java @@ -6,7 +6,7 @@ package com.unisinsight.project.exception; * @date 2020/8/10 19:53 * @since 1.0 */ -public enum BaseErrorCode implements ErrorCode{ +public enum BaseErrorCode implements ErrorCode { INTERNAL_EXCEPTION("00001", "系统内部异常"), INIT_EXCEPTION("00002", "系统初始化异常"), UNKNOWN_ERROR("00003", "未知错误"), @@ -46,7 +46,7 @@ public enum BaseErrorCode implements ErrorCode{ HTTP_REQUEST_TIME_OUT("00037", "HTTP请求超时"), HTTP_ERROR_CODE_400("00038", "HTTP错误码400"), HTTP_ERROR_CODE_404("00039", "HTTP错误码404"), - HTTP_ERROR_CODE_500("00040", "HTTP错误码500"), + HTTP_ERROR_CODE_500("500", "HTTP错误码500"), KAFKA_TOPICE_INVALID("00041", "kafka的topic无效"), KAFKA_MESSAGE_SEND_FAILURE("00042", " kafka消息发送失败"), DATABASE_ERROR("00043", "数据库错误"), @@ -149,20 +149,20 @@ public enum BaseErrorCode implements ErrorCode{ IPC_TYPE_GET_FAILED("00140", "获取IPC款型失败"), FORMAT_VALIDATE_ERROR("00141", "%s"), EXPORT_ERROR("00142", "导出EXCEL失败"), - SUCCESS("0000000000", "处理成功"); + SUCCESS("200", "处理成功"); - private String errorCode; + private String code; private String message; - BaseErrorCode(String errorCode, String message) { - this.errorCode = errorCode; + BaseErrorCode(String code, String message) { + this.code = code; this.message = message; } @Override - public String getErrorCode() { - return this.errorCode; + public String getCode() { + return this.code; } @Override diff --git a/nex-be/src/main/java/com/unisinsight/project/exception/BizException.java b/nex-be/src/main/java/com/unisinsight/project/exception/BizException.java deleted file mode 100644 index c51868c..0000000 --- a/nex-be/src/main/java/com/unisinsight/project/exception/BizException.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.unisinsight.project.exception; - -/** - * @author zhangmengfei [yf_zhang.mengfei@unisinsight.com] - * @description BizExceptions - * @date 2020/9/2 14:21 - * @since 1.0 - */ -public class BizException extends RuntimeException { - private int httpStatus = 500; - private String errorCode; - private Object body; - - public BizException(String message, Throwable cause, int httpStatus, String errorCode, Object body) { - super(message, cause); - this.httpStatus = httpStatus; - this.errorCode = errorCode; - this.body = body; - } - - public BizException(ErrorCode errorCode) { - super(errorCode.getMessage()); - this.errorCode = errorCode.getErrorCode(); - } - - public BizException(ErrorCode errorCode, Object data) { - super(errorCode.getMessage()); - this.errorCode = errorCode.getErrorCode(); - this.body = data; - } - - public BizException(ErrorCode errorCode, Object... params) { - super(String.format(errorCode.getMessage(), params)); - this.errorCode = errorCode.getErrorCode(); - } - - public BizException(ErrorCode errorCode, Throwable cause, Object... params) { - super(String.format(errorCode.getMessage(), params), cause); - this.errorCode = errorCode.getErrorCode(); - } - - public static BizExceptionBuilder builder() { - return new BizExceptionBuilder(); - } - - public static BizException of(ErrorCode errorCode) { - return new BizException(errorCode); - } - - public static BizException of(ErrorCode errorCode, Object... params) { - return new BizException(errorCode, params); - } - - public int getHttpStatus() { - return this.httpStatus; - } - - public void setHttpStatus(int httpStatus) { - this.httpStatus = httpStatus; - } - - public String getErrorCode() { - return this.errorCode; - } - - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } - - public Object getBody() { - return this.body; - } - - public void setBody(Object body) { - this.body = body; - } - - public static class BizExceptionBuilder { - private ErrorCode errorCode; - private Object[] params; - private Throwable cause; - private int status; - private T body; - - public BizExceptionBuilder() { - } - - public BizExceptionBuilder errorCode(ErrorCode errorCode) { - this.errorCode = errorCode; - return this; - } - - public BizExceptionBuilder params(Object... params) { - this.params = params; - return this; - } - - public BizExceptionBuilder cause(Throwable cause) { - this.cause = cause; - return this; - } - - public BizExceptionBuilder status(int status) { - this.status = status; - return this; - } - - public BizExceptionBuilder body(T body) { - this.body = body; - return this; - } - - public BizException build() { - return new BizException(String.format(this.errorCode.getMessage(), this.params), this.cause, this.status, this.errorCode.getErrorCode(), this.body); - } - } -} diff --git a/nex-be/src/main/java/com/unisinsight/project/exception/ErrorCode.java b/nex-be/src/main/java/com/unisinsight/project/exception/ErrorCode.java index 5938bcb..76012df 100644 --- a/nex-be/src/main/java/com/unisinsight/project/exception/ErrorCode.java +++ b/nex-be/src/main/java/com/unisinsight/project/exception/ErrorCode.java @@ -7,7 +7,7 @@ package com.unisinsight.project.exception; * @since 1.0 */ public interface ErrorCode { - String getErrorCode(); + String getCode(); String getMessage(); } \ No newline at end of file diff --git a/nex-be/src/main/java/com/unisinsight/project/exception/Result.java b/nex-be/src/main/java/com/unisinsight/project/exception/Result.java index 9d70e3a..68151d3 100644 --- a/nex-be/src/main/java/com/unisinsight/project/exception/Result.java +++ b/nex-be/src/main/java/com/unisinsight/project/exception/Result.java @@ -13,14 +13,14 @@ import lombok.Data; */ @Data @ApiModel("返回结果类") -public class Result implements ErrorCode { +public class Result { /** * 返回码 */ @ApiModelProperty("返回码") - @JsonProperty(value = "error_code") - private String errorCode; + @JsonProperty(value = "code") + private String code; /** * 返回信息 @@ -40,40 +40,40 @@ public class Result implements ErrorCode { } public Result(String errorCode, String message) { - this.errorCode = errorCode; + this.code = errorCode; this.message = message; } public Result(String errorCode, String message, T data) { - this.errorCode = errorCode; + this.code = errorCode; this.message = message; this.data = data; } public static Result successResult(T data) { - return new Result<>(BaseErrorCode.SUCCESS.getErrorCode(), BaseErrorCode.SUCCESS.getMessage(), data); + return new Result<>(BaseErrorCode.SUCCESS.getCode(), BaseErrorCode.SUCCESS.getMessage(), data); } public static Result successResult() { - return new Result<>(BaseErrorCode.SUCCESS.getErrorCode(), BaseErrorCode.SUCCESS.getMessage()); + return new Result<>(BaseErrorCode.SUCCESS.getCode(), BaseErrorCode.SUCCESS.getMessage()); } public static Result errorResult(ErrorCode errorCode) { - return new Result<>(errorCode.getErrorCode(), errorCode.getMessage()); + return new Result<>(errorCode.getCode(), errorCode.getMessage()); } public static Result errorResult(ErrorCode errorCode, T data) { - return new Result<>(errorCode.getErrorCode(), errorCode.getMessage(), data); + return new Result<>(errorCode.getCode(), errorCode.getMessage(), data); } public static Result errorResultMessage(ErrorCode errorCode, String message) { - return new Result<>(errorCode.getErrorCode(), message); + return new Result<>(errorCode.getCode(), message); } /** * 判断当前返回是否成功 */ public boolean success() { - return BaseErrorCode.SUCCESS.getErrorCode().equals(this.errorCode); + return BaseErrorCode.SUCCESS.getCode().equals(this.code); } } diff --git a/nex-be/src/main/java/com/unisinsight/project/service/DeviceService.java b/nex-be/src/main/java/com/unisinsight/project/service/DeviceService.java index 370c221..8169ecc 100644 --- a/nex-be/src/main/java/com/unisinsight/project/service/DeviceService.java +++ b/nex-be/src/main/java/com/unisinsight/project/service/DeviceService.java @@ -20,4 +20,6 @@ public interface DeviceService extends IService { Result delete(DeleteIdReq deleteIdReq); Result selectPageUser(DeviceReq deviceReq); + + Result query(DeviceReq deviceReq); } diff --git a/nex-be/src/main/java/com/unisinsight/project/service/DeviceUserMappingService.java b/nex-be/src/main/java/com/unisinsight/project/service/DeviceUserMappingService.java index c13c144..9351164 100644 --- a/nex-be/src/main/java/com/unisinsight/project/service/DeviceUserMappingService.java +++ b/nex-be/src/main/java/com/unisinsight/project/service/DeviceUserMappingService.java @@ -17,5 +17,5 @@ public interface DeviceUserMappingService extends IService { Result select(DeviceUserMappingReq deviceUserMappingReq); - Result loginUser(DeviceUserReq deviceUserReq); + Result loginUser(DeviceUserReq deviceUserReq); } diff --git a/nex-be/src/main/java/com/unisinsight/project/service/ImageService.java b/nex-be/src/main/java/com/unisinsight/project/service/ImageService.java index 3c45f43..09132fc 100644 --- a/nex-be/src/main/java/com/unisinsight/project/service/ImageService.java +++ b/nex-be/src/main/java/com/unisinsight/project/service/ImageService.java @@ -2,6 +2,7 @@ package com.unisinsight.project.service; import com.baomidou.mybatisplus.extension.service.IService; import com.unisinsight.project.entity.dao.Image; +import com.unisinsight.project.entity.req.DeleteIdReq; import com.unisinsight.project.entity.req.ImageReq; import com.unisinsight.project.exception.Result; @@ -13,4 +14,6 @@ import com.unisinsight.project.exception.Result; public interface ImageService extends IService { Result selectPage(ImageReq imageReq); + + Result delete(DeleteIdReq deleteIdReq); } diff --git a/nex-be/src/main/java/com/unisinsight/project/service/UserService.java b/nex-be/src/main/java/com/unisinsight/project/service/UserService.java index 26192ff..c05226f 100644 --- a/nex-be/src/main/java/com/unisinsight/project/service/UserService.java +++ b/nex-be/src/main/java/com/unisinsight/project/service/UserService.java @@ -21,4 +21,6 @@ public interface UserService extends IService { Result delete(DeleteIdReq deleteIdReq); Result selectPageUser(UserReq userReq); + + Result query(UserReq userReq); } diff --git a/nex-be/src/main/java/com/unisinsight/project/service/impl/DeviceServiceImpl.java b/nex-be/src/main/java/com/unisinsight/project/service/impl/DeviceServiceImpl.java index 9f05ddb..1fb4da5 100644 --- a/nex-be/src/main/java/com/unisinsight/project/service/impl/DeviceServiceImpl.java +++ b/nex-be/src/main/java/com/unisinsight/project/service/impl/DeviceServiceImpl.java @@ -104,6 +104,20 @@ public class DeviceServiceImpl extends ServiceImpl return Result.successResult(convert); } } + + + @Override + public Result query(DeviceReq deviceReq) { + Device device = deviceMapper.selectById(deviceReq.getId()); + + if (ObjectUtils.isEmpty(device)) { + log.info("查询终端返回为空"); + return Result.successResult(); + } + DeviceRes deviceRes = BeanUtil.copyProperties(device, DeviceRes.class); + log.info("查询终端返回:{}", JSONUtil.toJsonStr(deviceRes)); + return Result.successResult(deviceRes); + } } diff --git a/nex-be/src/main/java/com/unisinsight/project/service/impl/ImageServiceImpl.java b/nex-be/src/main/java/com/unisinsight/project/service/impl/ImageServiceImpl.java index 9f17ce3..26c1054 100644 --- a/nex-be/src/main/java/com/unisinsight/project/service/impl/ImageServiceImpl.java +++ b/nex-be/src/main/java/com/unisinsight/project/service/impl/ImageServiceImpl.java @@ -7,9 +7,11 @@ import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.unisinsight.project.entity.dao.Image; +import com.unisinsight.project.entity.req.DeleteIdReq; import com.unisinsight.project.entity.req.ImageReq; import com.unisinsight.project.entity.res.ImageRes; import com.unisinsight.project.entity.res.PageResult; +import com.unisinsight.project.exception.BaseErrorCode; import com.unisinsight.project.exception.Result; import com.unisinsight.project.mapper.ImageMapper; import com.unisinsight.project.service.ImageService; @@ -19,6 +21,10 @@ import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; /** * @author rdpnr_puzhi @@ -58,6 +64,44 @@ public class ImageServiceImpl extends ServiceImpl return Result.successResult(convert); } } + + @Override + public Result delete(DeleteIdReq deleteIdReq) { + Image image = imageMapper.selectById(deleteIdReq.getId()); + if (ObjectUtils.isNotEmpty(image)) { + boolean cleanUploadFile = cleanUploadFile(image.getStoragePath(), image.getImageName()); + if (cleanUploadFile) { + int deleted = imageMapper.deleteById(deleteIdReq.getId()); + log.info("镜像删除insert:{}", deleted); + if (deleted == 1) { + return Result.successResult(); + } + } + } + return Result.errorResult(BaseErrorCode.HTTP_ERROR_CODE_500); + } + + /** + * 根据文件名删除已上传的文件 + * + * @param fileName 文件名 + */ + private boolean cleanUploadFile(String uploadDir, String fileName) { + try { + Path filePath = Paths.get(uploadDir, fileName); + if (Files.exists(filePath)) { + // 删除文件 + Files.delete(filePath); + log.info("已删除文件: {}", filePath); + return true; + } else { + log.warn("文件不存在,无需删除: {}", filePath); + } + } catch (IOException e) { + log.error("删除文件失败: {}", e.getMessage(), e); + } + return false; + } } diff --git a/nex-be/src/main/java/com/unisinsight/project/service/impl/UserServiceImpl.java b/nex-be/src/main/java/com/unisinsight/project/service/impl/UserServiceImpl.java index 13f7528..46e7f38 100644 --- a/nex-be/src/main/java/com/unisinsight/project/service/impl/UserServiceImpl.java +++ b/nex-be/src/main/java/com/unisinsight/project/service/impl/UserServiceImpl.java @@ -94,14 +94,26 @@ public class UserServiceImpl extends ServiceImpl IPage userPage = userMapper.selectPage(page, queryWrapper); log.info("分页查询用户返回:{}", JSONUtil.toJsonStr(userPage)); - if (CollectionUtil.isEmpty(userPage.getRecords())){ + if (CollectionUtil.isEmpty(userPage.getRecords())) { log.info("分页查询用户返回为空"); return Result.successResult(); - }else { + } else { PageResult convert = PageResult.convertIPage(userPage, UserRes.class); return Result.successResult(convert); } } + + @Override + public Result query(UserReq userReq) { + User user = userMapper.selectById(userReq.getId()); + if (ObjectUtils.isEmpty(user)) { + log.info("查询用户返回为空"); + return Result.successResult(); + } + UserRes userRes = BeanUtil.copyProperties(user, UserRes.class); + log.info("查询用户返回:{}", JSONUtil.toJsonStr(userRes)); + return Result.successResult(userRes); + } } diff --git a/nex-be/src/main/java/com/unisinsight/project/util/DigestUtil.java b/nex-be/src/main/java/com/unisinsight/project/util/DigestUtil.java new file mode 100644 index 0000000..6ced66b --- /dev/null +++ b/nex-be/src/main/java/com/unisinsight/project/util/DigestUtil.java @@ -0,0 +1,171 @@ +package com.unisinsight.project.util; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.DESedeKeySpec; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class DigestUtil { + /** 算法名称 */ + private static final String ALGORITHM = "DESede"; + /** 16进制字母 */ + private static final char[] HEX_DIGITS={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; + + /** + * @param decript 要加密的字符串 + * @return 加密的字符串 + * SHA1加密 + */ + public final static String SHA1(String decript) { + try { + MessageDigest digest = MessageDigest + .getInstance("SHA-1"); + digest.update(decript.getBytes()); + byte messageDigest[] = digest.digest(); + // Create Hex String + StringBuffer hexString = new StringBuffer(); + // 字节数组转换为 十六进制 数 + for (int i = 0; i < messageDigest.length; i++) { + String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); + if (shaHex.length() < 2) { + hexString.append(0); + } + hexString.append(shaHex); + } + return hexString.toString(); + + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return ""; + } + + + /** + * 3DES加密,key必须是长度大于等于 3*8 = 24 位 + * @param src + * @param key + * @return + * @throws Exception + */ + public static String encrypt3DES(String src, String key) { + byte[] keyBytes = key.getBytes(); + try { + DESedeKeySpec dks = new DESedeKeySpec(keyBytes); + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); + SecretKey securekey = keyFactory.generateSecret(dks); + + Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); + cipher.init(Cipher.ENCRYPT_MODE, securekey); + byte[] b=cipher.doFinal(src.getBytes()); + return StringUtil.byte2hex(b); + } catch (Exception e) { + return null; + } + } + + /** + * 3DESECB解密,key必须是长度大于等于 3*8 = 24 位 + * @param src + * @param key + * @return + * @throws Exception + */ + public static String decrypt3DES(String src, String key) { + + byte[] keyBytes = key.getBytes(); + try { + //--通过base64,将字符串转成byte数组 + byte[] bytesrc = StringUtil.hex2byte(src); + //--解密的key + DESedeKeySpec dks = new DESedeKeySpec(keyBytes); + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); + SecretKey securekey = keyFactory.generateSecret(dks); + + //--Chipher对象解密 + Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, securekey); + byte[] retByte = cipher.doFinal(bytesrc); + return new String(retByte); + } catch (Exception e) { + return null; + } + } + + /** + * + * Description:md5加密 + * @Create_by:JH + * @Create_date:2014-9-9 + * @Last_Edit_By: + * @Edit_Description + * @Create_Version:exinhua 1.0 + */ + public static String encryptMd5(String src) { + if(StringUtil.isEmpty(src)) { + return src; + } + try { + byte[] btInput = src.getBytes(); + // 获得MD5摘要算法的 MessageDigest 对象 + MessageDigest mdInst = MessageDigest.getInstance("MD5"); + // 使用指定的字节更新摘要 + mdInst.update(btInput); + // 获得密文 + byte[] md = mdInst.digest(); + // 把密文转换成十六进制的字符串形式 + return byteToHexString(md); + } catch (Exception e) { + throw new RuntimeException("error occurated when encrypt", e); + } + } + public static String encryptMd5(byte[] btInput) { + try { + // 获得MD5摘要算法的 MessageDigest 对象 + MessageDigest mdInst = MessageDigest.getInstance("MD5"); + // 使用指定的字节更新摘要 + mdInst.update(btInput); + // 获得密文 + byte[] md = mdInst.digest(); + // 把密文转换成十六进制的字符串形式 + return byteToHexString(md); + } catch (Exception e) { + throw new RuntimeException("error occurated when encrypt", e); + } + } + + /** + * 对输入进行sha1加密后,在进行16进制转换 + * @param value + * @return + */ + public static String hexSHA1(String value) { + try { + MessageDigest md = MessageDigest.getInstance("SHA-1"); + md.update(value.getBytes("utf-8")); + byte[] digest = md.digest(); + return byteToHexString(digest); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + + /** + * 字节数组转换成16进制表示 + * @param bytes + * @return + */ + public static String byteToHexString(byte[] bytes) { + int j = bytes.length; + char[] str = new char[j * 2]; + int k = 0; + for (int i = 0; i < j; i++) { + byte byte0 = bytes[i]; + str[k++] = HEX_DIGITS[byte0 >>> 4 & 0xf]; + str[k++] = HEX_DIGITS[byte0 & 0xf]; + } + return new String(str); + } +} diff --git a/nex-be/src/main/java/com/unisinsight/project/util/StringUtil.java b/nex-be/src/main/java/com/unisinsight/project/util/StringUtil.java new file mode 100644 index 0000000..64483be --- /dev/null +++ b/nex-be/src/main/java/com/unisinsight/project/util/StringUtil.java @@ -0,0 +1,232 @@ +package com.unisinsight.project.util; + +/** + * 字符串工具类 + * + */ +public class StringUtil { + + public static final String[] HEX_ARRAYS = { "0", "1", "2", "3", "4", "5", + "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; + + /** + *  判断value是否是null或者其length为0 + * + * @param value + * @return + */ + public static boolean isEmpty(String value) { + return value == null || value.length() == 0; + } + + /** + * 判断value是否不是null且其length>0 + * + * @param value + * @return + */ + public static boolean isNotEmpty(String value) { + return !isEmpty(value); + } + + /** + * trim操作 + * + * @param value + * @return + */ + public static String trim(String value) { + if (value == null) { + return null; + } + return value.trim(); + } + + /** + * byte string to hex string + * + * @param b + * @return + */ + public static String byte2hex(byte[] b) { + if (b == null) { + return null; + } + if (b.length == 0) { + return ""; + } + StringBuilder retBuilder = new StringBuilder(); + for (int n = 0; n < b.length; ++n) { + retBuilder.append(HEX_ARRAYS[(b[n] & 0xF0) >> 4]); + retBuilder.append(HEX_ARRAYS[b[n] & 0x0F]); + } + return retBuilder.toString(); + } + + /** + * hex string to byte string + * + * @param str + * @return + */ + public static byte[] hex2byte(String str) { + if (str == null) + return null; + str = str.trim(); + int len = str.length(); + if ((len == 0) || (len % 2 == 1)) + return null; + byte[] b = new byte[len / 2]; + byte tmp = 0; + char[] strs = str.toCharArray(); + for (int i = 0; i < len; i++) { + byte t = 0; + if (strs[i] >= '0' && strs[i] <= '9') { + t = (byte) (strs[i] - '0'); + } else if (strs[i] >= 'A' && strs[i] <= 'F') { + t = (byte) (strs[i] - 'A' + 10); + } else if (strs[i] >= 'a' && strs[i] <= 'f') { + t = (byte) (strs[i] - 'a' + 10); + } + if ((i & 0x1) == 1) { + tmp <<= 4; + tmp += t; + b[i / 2] = tmp; + tmp = 0; + } else { + tmp = t; + } + } + return b; + } + + /** + * 判断一个字符串是否只包含数字(10进制)字符 + * + * @param str + * @return + */ + public static boolean isNumeric(String str) { + if (isEmpty(str)) { + return false; + } + char[] arr = str.toCharArray(); + for (char c : arr) { + if (!Character.isDigit(c)) { + return false; + } + } + return true; + } + + /** + * 混淆字串串(显示前pn个字符和后tn个字符,其余全部用*填充) + * + * @param source + * @param pn + * @param tn + * @return + */ + public static String mix(String source, int pn, int tn) { + return mix(source, pn, tn, '*'); + } + + /** + * 混淆字串串(显示前pn个字符和后tn个字符,其余前部用mixChar填充) + * + * @param source + * @param pn + * @param tn + * @param mixChar + * @return + */ + public static String mix(String source, int pn, int tn, char mixChar) { + if (source == null || source.length() <= pn + tn) { + return source; + } + int len = source.length(); + StringBuilder tmp = new StringBuilder(source.length()); + char[] mobileAs = source.toCharArray(); + for (int i = 0; i < pn; i++) { + tmp.append(mobileAs[i]); + } + for (int i = 0; i < len - (pn + tn); i++) { + tmp.append(mixChar); + } + for (int i = len - tn; i < len; i++) { + tmp.append(mobileAs[i]); + } + + return tmp.toString(); + } + + /** + * 获取字符串长度(全角2,半角1) + * @param value + * @return + */ + public static final int getLength(String value) { + if(StringUtil.isEmpty(value)) { + return 0; + } + int len = 0; + for(char c : value.toCharArray()) { + len++; + if(isSbcCase(c)) { + len++; + } + } + return len; + } + + /** + * 判断字符是否是半角 + * @param c + * @return + */ + public static final boolean isDbcCase(char c) { + int k = 0x80; + return c / k == 0 ? true : false; + } + /** + * 判断是否时全角 + * @param c + * @return + */ + public static final boolean isSbcCase(char c) { + return isDbcCase(c); + } + /** + * 判断是否都是数字 + * @param value + * @return + */ + public static final boolean isAllDigits(String value) { + if(StringUtil.isEmpty(value)) { + return true; + } + for(char c : value.toCharArray()) { + if(c < '0' || c > '9') { + return false; + } + } + return true; + } + + /** + * 在指定的字符串前面填充0,直到字段串的长度达到指定的长度 + * 示例:输入6, 2 ---> 返回06 + * @param data 需要被填充的字符串 + * @param fillStr 需要填充得字符串 + * @param length 目标字符串的长度 + * @return 返回填充后的字符串 + */ + public static String frontFillStr(String data, String fillStr, int length) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length-data.length(); i++) { + sb.append(fillStr); + } + return sb.append(data).toString(); + } + +}