Browse Source

升级 hutool, 格式化代码

zhenghao 4 months ago
parent
commit
26a86bacc5

+ 1 - 1
pom.xml

@@ -96,7 +96,7 @@
 		<dependency>
 			<groupId>cn.hutool</groupId>
 			<artifactId>hutool-all</artifactId>
-			<version>5.8.15</version>
+			<version>5.8.16</version>
 		</dependency>
 		<dependency>
 			<groupId>org.apache.commons</groupId>

+ 10 - 0
src/main/java/cn/jlsxwkj/common/exception/OpenFileFailException.java

@@ -0,0 +1,10 @@
+package cn.jlsxwkj.common.exception;
+
+/**
+ * @author zh
+ */
+public class OpenFileFailException extends CustomException {
+    public OpenFileFailException(String message) {
+        super(message);
+    }
+}

+ 12 - 3
src/main/java/cn/jlsxwkj/common/utils/MergeDocuments.java

@@ -3,7 +3,10 @@ package cn.jlsxwkj.common.utils;
 import cn.hutool.core.util.ArrayUtil;
 import org.springframework.ai.document.Document;
 
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Optional;
 import java.util.stream.Collectors;
 
 /**
@@ -20,9 +23,15 @@ public class MergeDocuments {
     public static List<Document> mergeDocuments(List<Document> documentList) {
         ArrayList<Document> mergeDocuments = new ArrayList<>();
         //根据文档来源进行分组
-        for (var docListEntry : documentList.stream().collect(Collectors.groupingBy(document -> (String) document.getMetadata().get(SplitDocument.FILE_NAME))).entrySet()) {
+        for (var docListEntry : documentList.stream()
+                .collect(Collectors.groupingBy(
+                        document -> (String) document.getMetadata().get(SplitDocument.FILE_NAME)
+                )).entrySet()) {
             //获取最大的段落结束编码
-            Optional<Document> documents = docListEntry.getValue().stream().max(Comparator.comparing(document -> (int) document.getMetadata().get(SplitDocument.END_PARAGRAPH_NUMBER)));
+            Optional<Document> documents = docListEntry.getValue().stream()
+                    .max(Comparator.comparing(
+                            document -> (int) document.getMetadata().get(SplitDocument.END_PARAGRAPH_NUMBER)
+                    ));
             if (documents.isEmpty()) {
                 continue;
             }

+ 5 - 2
src/main/java/cn/jlsxwkj/common/utils/SplitDocument.java

@@ -32,7 +32,9 @@ public class SplitDocument {
             return null;
         }
         ArrayList<Document> readDocuments = new ArrayList<>();
-        List<String> paragraphs = Arrays.stream(document.split("\n")).distinct().dropWhile(""::equals).collect(Collectors.toList());
+        List<String> paragraphs = Arrays.stream(document.split("\n")).distinct()
+                .dropWhile(""::equals)
+                .collect(Collectors.toList());
         //采用窗口滑动读取
         int startIndex = 0;
         int endIndex = startIndex + windowSize;
@@ -40,7 +42,8 @@ public class SplitDocument {
             readDocuments.add(toDocument(paragraphs, fileName, startIndex + 1, paragraphs.size()));
         } else {
             for (; endIndex <= paragraphs.size(); startIndex++, endIndex++) {
-                readDocuments.add(toDocument(ListUtil.sub(paragraphs, startIndex, endIndex), fileName, startIndex + 1, endIndex));
+                List<String> sub = ListUtil.sub(paragraphs, startIndex, endIndex);
+                readDocuments.add(toDocument(sub, fileName, startIndex + 1, endIndex));
             }
         }
         return readDocuments;

+ 17 - 12
src/main/java/cn/jlsxwkj/moudles/chat/ChatService.java

@@ -4,10 +4,7 @@ import cn.dev33.satoken.SaManager;
 import cn.hutool.core.lang.Tuple;
 import cn.hutool.crypto.digest.MD5;
 import cn.jlsxwkj.common.config.UserConfig;
-import cn.jlsxwkj.common.exception.CustomException;
-import cn.jlsxwkj.common.exception.FileTypeDoesNotSupportException;
-import cn.jlsxwkj.common.exception.InsertFailException;
-import cn.jlsxwkj.common.exception.UnknownException;
+import cn.jlsxwkj.common.exception.*;
 import cn.jlsxwkj.common.utils.FileType;
 import cn.jlsxwkj.common.utils.Log;
 import cn.jlsxwkj.common.utils.MergeDocuments;
@@ -89,7 +86,9 @@ public class ChatService {
      * @return 文本内容
      */
     public String search(String keyword) {
-        return mergeDocuments(vectorStore.similaritySearch(SearchRequest.query(keyword).withSimilarityThreshold(0.5)));
+        SearchRequest searchRequest = SearchRequest.query(keyword).withSimilarityThreshold(0.5);
+        List<Document> documents = vectorStore.similaritySearch(searchRequest);
+        return mergeDocuments(documents);
     }
 
     /**
@@ -121,7 +120,11 @@ public class ChatService {
         String fileName = supportFile.get(1);
         String fileTypeCn = supportFile.get(2);
         DocumentReader reader = supportFile.get(3);
-        String context = fileTypeCn + " :: " + fileName + " ====> " + mergeDocuments(reader.get()) + "\n" + "↑ " + message;
+        String format = """
+                %s :: %s ====> %s
+                ↑ %s
+                """;
+        String context = String.format(format, fileTypeCn, fileName, mergeDocuments(reader.get()), message);
         UserMessage userMessage = new UserMessage(context);
         Log.info(this.getClass(), context);
         return stream(message, userMessage);
@@ -135,7 +138,8 @@ public class ChatService {
      */
     private String mergeDocuments(List<Document> documents) {
         return MergeDocuments.mergeDocuments(documents).stream()
-                .map(Document::getContent).collect(Collectors.joining("\n"));
+                .map(Document::getContent)
+                .collect(Collectors.joining("\n"));
     }
 
     /**
@@ -157,14 +161,15 @@ public class ChatService {
             listMessage.add(new SystemMessage(userConfig.getSysMessage()));
         }
         if (listMessage.size() > userConfig.getMaxListMessageLength()) {
-            listMessage = listMessage.subList(listMessage.size() - userConfig.getMaxListMessageLength(), listMessage.size())
-                    .stream()
+            int start = listMessage.size() - userConfig.getMaxListMessageLength();
+            listMessage = listMessage.subList(start, listMessage.size()).stream()
                     .filter(msg -> !msg.getContent().equals(userConfig.getSysMessage()))
                     .map(msg -> {
                         if (msg.getRole().equals(UserRole.ASSISTANT)) {
                             String content = msg.getContent();
                             if (content.length() > userConfig.getMaxMessageLength()) {
-                                return new AssistantMessage(content.substring(0, userConfig.getMaxMessageLength()));
+                                String assistantMessage = content.substring(0, userConfig.getMaxMessageLength());
+                                return new AssistantMessage(assistantMessage);
                             }
                         }
                         return msg;
@@ -223,11 +228,11 @@ public class ChatService {
      * @return 元组
      */
     private Tuple isSupportFile(MultipartFile file) throws CustomException {
-        byte[] bytes = new byte[0];
+        byte[] bytes;
         try {
             bytes = file.getBytes();
         } catch (IOException e) {
-            e.printStackTrace();
+            throw new OpenFileFailException("读取文件失败");
         }
         String[] split = Objects.requireNonNull(file.getOriginalFilename()).split("\\.");
         String fileType = split[split.length - 1].toLowerCase(Locale.ROOT);

+ 3 - 1
src/main/java/cn/jlsxwkj/moudles/chathistory/ChatHistoryService.java

@@ -18,7 +18,9 @@ public class ChatHistoryService {
     private ChatHistoryMapper chatHistoryMapper;
 
     @Transactional(rollbackFor = InsertFailException.class)
-    public void insert(String userId, String userQ, String chatA) throws InsertFailException {
+    public void insert(String userId,
+                       String userQ,
+                       String chatA) throws InsertFailException {
         Integer rows = chatHistoryMapper.insert(userId, userQ, chatA);
         if (rows < 1) {
             throw new InsertFailException("插入失败");

+ 2 - 1
src/main/java/cn/jlsxwkj/moudles/userlist/UserListController.java

@@ -22,7 +22,8 @@ public class UserListController {
     @Operation(summary = "登录")
     @PostMapping("/login")
     @SaIgnore
-    public UserVO login(@RequestParam String userName, @RequestParam String userPassword) throws CustomException {
+    public UserVO login(@RequestParam String userName,
+                        @RequestParam String userPassword) throws CustomException {
         return userListService.checkOrAddUser(userName, userPassword);
     }