diff --git a/src/main/java/com/laker/postman/model/Workspace.java b/src/main/java/com/laker/postman/model/Workspace.java index e49b7f76..5eb54280 100644 --- a/src/main/java/com/laker/postman/model/Workspace.java +++ b/src/main/java/com/laker/postman/model/Workspace.java @@ -2,6 +2,8 @@ import lombok.Data; +import java.nio.file.Path; + // Workspace模型类 @Data public class Workspace { @@ -10,7 +12,7 @@ public class Workspace { private String description; // 工作空间描述 private WorkspaceType type; // LOCAL/GIT private GitRepoSource gitRepoSource; // 仓库来源:INITIALIZED(本地初始化)/ CLONED(远程克隆) - private String path; // 本地路径 + private Path path; // 本地路径 private String gitRemoteUrl; // Git远程仓库地址 private String currentBranch; // 当前分支名称 private String remoteBranch; // 当前跟踪的远程分支名称 @@ -23,4 +25,5 @@ public class Workspace { private GitAuthType gitAuthType; // 认证类型 private String sshPrivateKeyPath; // SSH 私钥文件路径 private String sshPassphrase; // SSH 私钥密码(可选) + } \ No newline at end of file diff --git a/src/main/java/com/laker/postman/panel/collections/left/RequestCollectionsLeftPanel.java b/src/main/java/com/laker/postman/panel/collections/left/RequestCollectionsLeftPanel.java index 1700cd85..7e8bdbf2 100644 --- a/src/main/java/com/laker/postman/panel/collections/left/RequestCollectionsLeftPanel.java +++ b/src/main/java/com/laker/postman/panel/collections/left/RequestCollectionsLeftPanel.java @@ -44,6 +44,7 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; +import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -93,7 +94,7 @@ private JScrollPane getTreeScrollPane() { rootTreeNode = new DefaultMutableTreeNode(ROOT); treeModel = new DefaultTreeModel(rootTreeNode); Workspace currentWorkspace = WorkspaceService.getInstance().getCurrentWorkspace(); - String filePath = SystemUtil.getCollectionPathForWorkspace(currentWorkspace); + Path filePath = SystemUtil.getCollectionPathForWorkspace(currentWorkspace); // 初始化持久化工具 persistence = new RequestsPersistence(filePath, rootTreeNode, treeModel); // 创建树组件 @@ -806,7 +807,7 @@ public void locateAndSelectRequest(String requestId) { /** * 切换到指定工作区的请求集合文件,并刷新树UI */ - public void switchWorkspaceAndRefreshUI(String collectionFilePath) { + public void switchWorkspaceAndRefreshUI(Path collectionFilePath) { if (persistence != null) { persistence.setDataFilePath(collectionFilePath); } @@ -950,7 +951,7 @@ private void performCollectionMove(DefaultMutableTreeNode collectionNode, Worksp DefaultMutableTreeNode copiedNode = deepCopyGroupNode(collectionNode); // 2. 获取目标工作区的集合文件路径 - String targetCollectionPath = SystemUtil.getCollectionPathForWorkspace(targetWorkspace); + Path targetCollectionPath = SystemUtil.getCollectionPathForWorkspace(targetWorkspace); // 3. 创建目标工作区的持久化工具 DefaultMutableTreeNode targetRootNode = new DefaultMutableTreeNode(ROOT); diff --git a/src/main/java/com/laker/postman/panel/env/EnvironmentPanel.java b/src/main/java/com/laker/postman/panel/env/EnvironmentPanel.java index 82749ce7..662e1a83 100644 --- a/src/main/java/com/laker/postman/panel/env/EnvironmentPanel.java +++ b/src/main/java/com/laker/postman/panel/env/EnvironmentPanel.java @@ -42,6 +42,7 @@ import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -704,7 +705,7 @@ private void syncComboBoxOrder() { /** * 切换到指定工作区的环境数据文件,并刷新UI */ - public void switchWorkspaceAndRefreshUI(String envFilePath) { + public void switchWorkspaceAndRefreshUI(Path envFilePath) { EnvironmentService.setDataFilePath(envFilePath); this.refreshUI(); // 同步刷新顶部环境下拉框 @@ -856,10 +857,10 @@ private void performEnvironmentMove(Environment environment, Workspace targetWor } // 2. 获取目标工作区的环境文件路径 - String targetEnvPath = SystemUtil.getEnvPathForWorkspace(targetWorkspace); + Path targetEnvPath = SystemUtil.getEnvPathForWorkspace(targetWorkspace); // 3. 临时切换到目标工作区的环境服务 - String originalDataFilePath = EnvironmentService.getDataFilePath(); + Path originalDataFilePath = EnvironmentService.getDataFilePath(); try { // 切换到目标工作区 EnvironmentService.setDataFilePath(targetEnvPath); diff --git a/src/main/java/com/laker/postman/panel/topmenu/TopMenuBarPanel.java b/src/main/java/com/laker/postman/panel/topmenu/TopMenuBarPanel.java index 4e8160c8..6f88b8e7 100644 --- a/src/main/java/com/laker/postman/panel/topmenu/TopMenuBarPanel.java +++ b/src/main/java/com/laker/postman/panel/topmenu/TopMenuBarPanel.java @@ -84,7 +84,7 @@ private void addFileMenu() { private void openLogDirectory() { try { - Desktop.getDesktop().open(new File(SystemUtil.LOG_DIR)); + Desktop.getDesktop().open(SystemUtil.LOG_DIR.toFile()); } catch (IOException ex) { log.error("Failed to open log directory", ex); JOptionPane.showMessageDialog(null, diff --git a/src/main/java/com/laker/postman/panel/topmenu/setting/SettingManager.java b/src/main/java/com/laker/postman/panel/topmenu/setting/SettingManager.java index 1b6d89b5..2988e2d7 100644 --- a/src/main/java/com/laker/postman/panel/topmenu/setting/SettingManager.java +++ b/src/main/java/com/laker/postman/panel/topmenu/setting/SettingManager.java @@ -7,10 +7,11 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import java.nio.file.Path; import java.util.Properties; public class SettingManager { - private static final String CONFIG_FILE = SystemUtil.getUserHomeEasyPostmanPath() + "easy_postman_settings.properties"; + private static final Path CONFIG_FILE = SystemUtil.EASY_POSTMAN_HOME.resolve("easy_postman_settings.properties"); private static final Properties props = new Properties(); // 私有构造函数,防止实例化 @@ -23,7 +24,7 @@ private SettingManager() { } public static void load() { - File file = new File(CONFIG_FILE); + File file = CONFIG_FILE.toFile(); if (file.exists()) { try (FileInputStream fis = new FileInputStream(file)) { props.load(fis); @@ -34,7 +35,7 @@ public static void load() { } public static void save() { - try (FileOutputStream fos = new FileOutputStream(CONFIG_FILE)) { + try (FileOutputStream fos = new FileOutputStream(CONFIG_FILE.toFile())) { props.store(fos, "EasyPostman Settings"); } catch (IOException e) { // ignore diff --git a/src/main/java/com/laker/postman/panel/workspace/components/WorkspaceCreateDialog.java b/src/main/java/com/laker/postman/panel/workspace/components/WorkspaceCreateDialog.java index ae6cfc1e..5ebd341b 100644 --- a/src/main/java/com/laker/postman/panel/workspace/components/WorkspaceCreateDialog.java +++ b/src/main/java/com/laker/postman/panel/workspace/components/WorkspaceCreateDialog.java @@ -23,6 +23,9 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; /** * 创建工作区对话框 @@ -120,16 +123,16 @@ private void initComponents() { * 设置默认的工作区路径 */ private void setDefaultWorkspacePath() { - String defaultWorkspaceDir = SystemUtil.getUserHomeEasyPostmanPath() + WORKSPACES; - pathField.setText(defaultWorkspaceDir); + Path defaultWorkspaceDir = SystemUtil.EASY_POSTMAN_HOME.resolve(WORKSPACES); + pathField.setText(defaultWorkspaceDir.toString()); } /** * 根据工作区名称生成符合路径规则的目录名 */ - private String generatePathFromName(String name) { + private Path generatePathFromName(String name) { if (name == null || name.trim().isEmpty()) { - return ""; + return null; } // 清理名称,生成合法的目录名 @@ -143,7 +146,7 @@ private String generatePathFromName(String name) { cleanName = RandomUtil.randomString(10); // 如果清理后为空,使用随机字符串 } - return SystemUtil.getUserHomeEasyPostmanPath() + WORKSPACES + File.separator + cleanName; + return SystemUtil.EASY_POSTMAN_HOME.resolve(WORKSPACES).resolve(cleanName); } @Override @@ -256,8 +259,8 @@ public void changedUpdate(DocumentEvent e) { */ private void updatePathFromName() { String name = nameField.getText(); - String generatedPath = generatePathFromName(name); - pathField.setText(generatedPath); + Path generatedPath = generatePathFromName(name); + pathField.setText(generatedPath == null ? "":generatedPath.toString()); } private JPanel createBasicInfoPanel() { @@ -426,17 +429,18 @@ private void browseForPath(ActionEvent e) { chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setDialogTitle(I18nUtil.getMessage(MessageKeys.WORKSPACE_SELECT_PATH)); - String currentPath = pathField.getText().trim(); - if (currentPath.isEmpty()) { - currentPath = SystemUtil.getUserHomeEasyPostmanPath() + WORKSPACES; + String currentPathStr = pathField.getText().trim(); + Path currentPath = SystemUtil.EASY_POSTMAN_HOME.resolve(WORKSPACES); + if (!currentPathStr.isEmpty()) { + currentPath = Paths.get(currentPathStr); } // 确保父目录存在 - File parentDir = new File(currentPath).getParentFile(); - if (parentDir != null && parentDir.exists()) { - chooser.setCurrentDirectory(parentDir); + Path parentDir = currentPath.getParent(); + if (parentDir != null && Files.exists(parentDir)) { + chooser.setCurrentDirectory(parentDir.toFile()); } else { - chooser.setCurrentDirectory(new File(SystemUtil.getUserHomeEasyPostmanPath())); + chooser.setCurrentDirectory(SystemUtil.EASY_POSTMAN_HOME.toFile()); } int result = chooser.showOpenDialog(this); @@ -558,7 +562,7 @@ private Workspace buildWorkspace() { Workspace ws = new Workspace(); ws.setName(nameField.getText().trim()); ws.setDescription(descriptionArea.getText().trim()); - ws.setPath(pathField.getText().trim()); + ws.setPath(Paths.get(pathField.getText().trim())); if (localTypeRadio.isSelected()) { ws.setType(WorkspaceType.LOCAL); diff --git a/src/main/java/com/laker/postman/panel/workspace/components/WorkspaceDetailPanel.java b/src/main/java/com/laker/postman/panel/workspace/components/WorkspaceDetailPanel.java index 5ea05c99..5f5bdbd3 100644 --- a/src/main/java/com/laker/postman/panel/workspace/components/WorkspaceDetailPanel.java +++ b/src/main/java/com/laker/postman/panel/workspace/components/WorkspaceDetailPanel.java @@ -59,7 +59,7 @@ public WorkspaceDetailPanel(Workspace workspace) { gbc.gridx = 1; gbc.weightx = 1.0; gbc.fill = GridBagConstraints.HORIZONTAL; - JLabel pathLabel = new JLabel(workspace.getPath()); + JLabel pathLabel = new JLabel(workspace.getPath().toString()); infoSection.add(pathLabel, gbc); // 描述 diff --git a/src/main/java/com/laker/postman/service/ClientCertificateService.java b/src/main/java/com/laker/postman/service/ClientCertificateService.java index 3324be3a..537fbf40 100644 --- a/src/main/java/com/laker/postman/service/ClientCertificateService.java +++ b/src/main/java/com/laker/postman/service/ClientCertificateService.java @@ -11,6 +11,7 @@ import lombok.extern.slf4j.Slf4j; import java.io.File; +import java.nio.file.Path; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; @@ -23,7 +24,7 @@ */ @Slf4j public class ClientCertificateService { - private static final String CERT_CONFIG_FILE = SystemUtil.getUserHomeEasyPostmanPath() + "client_certificates.json"; + private static final Path CERT_CONFIG_FILE = SystemUtil.EASY_POSTMAN_HOME.resolve("client_certificates.json"); private static final List certificates = new CopyOnWriteArrayList<>(); private ClientCertificateService() { @@ -38,7 +39,7 @@ private ClientCertificateService() { * 从文件加载证书配置 */ public static void load() { - File file = new File(CERT_CONFIG_FILE); + File file = CERT_CONFIG_FILE.toFile(); if (!file.exists()) { log.info("Client certificate config file not found, creating new one"); return; @@ -63,7 +64,7 @@ public static void load() { */ public static void save() { try { - File file = new File(CERT_CONFIG_FILE); + File file = CERT_CONFIG_FILE.toFile(); File parent = file.getParentFile(); if (parent != null && !parent.exists()) { boolean created = parent.mkdirs(); diff --git a/src/main/java/com/laker/postman/service/EnvironmentService.java b/src/main/java/com/laker/postman/service/EnvironmentService.java index 170f9474..780c3a03 100644 --- a/src/main/java/com/laker/postman/service/EnvironmentService.java +++ b/src/main/java/com/laker/postman/service/EnvironmentService.java @@ -13,6 +13,7 @@ import java.io.File; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; @@ -42,7 +43,7 @@ private EnvironmentService() { private static final ThreadLocal> temporaryVariables = ThreadLocal.withInitial(ConcurrentHashMap::new); // 当前数据文件路径 - private static String currentDataFilePath; + private static Path currentDataFilePath; static { loadEnvironments(); @@ -68,7 +69,7 @@ public static void clearTemporaryVariables() { /** * 获取当前数据文件路径 */ - public static String getDataFilePath() { + public static Path getDataFilePath() { if (currentDataFilePath != null) { return currentDataFilePath; } @@ -80,8 +81,8 @@ public static String getDataFilePath() { /** * 切换环境变量数据文件路径,并重新加载 */ - public static void setDataFilePath(String path) { - if (path == null || path.isBlank()) return; + public static void setDataFilePath(Path path) { + if (path == null) return; currentDataFilePath = path; loadEnvironmentsFromPath(path); } @@ -89,8 +90,8 @@ public static void setDataFilePath(String path) { /** * 从指定路径加载环境变量 */ - private static void loadEnvironmentsFromPath(String filePath) { - File file = new File(filePath); + private static void loadEnvironmentsFromPath(Path filePath) { + File file = filePath.toFile(); if (!file.exists()) { log.info("环境变量文件不存在: {}, 将创建默认环境", filePath); createDefaultEnvironments(); @@ -129,7 +130,7 @@ public static void loadEnvironments() { loadEnvironmentsFromPath(currentDataFilePath); } else { Workspace currentWorkspace = WorkspaceService.getInstance().getCurrentWorkspace(); - String filePath = SystemUtil.getEnvPathForWorkspace(currentWorkspace); + Path filePath = SystemUtil.getEnvPathForWorkspace(currentWorkspace); loadEnvironmentsFromPath(filePath); } } @@ -165,7 +166,7 @@ private static void createDefaultEnvironments() { */ public static void saveEnvironments() { try { - String filePath; + Path filePath; if (currentDataFilePath != null) { filePath = currentDataFilePath; } else { @@ -173,7 +174,7 @@ public static void saveEnvironments() { filePath = SystemUtil.getEnvPathForWorkspace(currentWorkspace); } - File file = new File(filePath); + File file = filePath.toFile(); File parentDir = file.getParentFile(); if (!parentDir.exists()) { parentDir.mkdirs(); diff --git a/src/main/java/com/laker/postman/service/HistoryPersistenceManager.java b/src/main/java/com/laker/postman/service/HistoryPersistenceManager.java index 1a59bc24..a664d1d5 100644 --- a/src/main/java/com/laker/postman/service/HistoryPersistenceManager.java +++ b/src/main/java/com/laker/postman/service/HistoryPersistenceManager.java @@ -26,7 +26,7 @@ */ @Slf4j public class HistoryPersistenceManager { - private static final String HISTORY_FILE = SystemUtil.getUserHomeEasyPostmanPath() + "request_history.json"; + private static final Path HISTORY_FILE = SystemUtil.EASY_POSTMAN_HOME.resolve("request_history.json"); private static HistoryPersistenceManager instance; private final List historyItems = new CopyOnWriteArrayList<>(); @@ -45,7 +45,7 @@ public static synchronized HistoryPersistenceManager getInstance() { private void ensureHistoryDirExists() { try { - Path historyDir = Paths.get(SystemUtil.getUserHomeEasyPostmanPath()); + Path historyDir = SystemUtil.EASY_POSTMAN_HOME; if (!Files.exists(historyDir)) { Files.createDirectories(historyDir); } @@ -104,7 +104,7 @@ public void saveHistory() { // 写入文件 String jsonString = JSONUtil.toJsonPrettyStr(jsonArray); - Files.writeString(Paths.get(HISTORY_FILE), jsonString, StandardCharsets.UTF_8); + Files.writeString(HISTORY_FILE, jsonString, StandardCharsets.UTF_8); } catch (IOException e) { log.error("Failed to save history: {}", e.getMessage()); } @@ -123,13 +123,13 @@ private void saveHistoryAsync() { * 加载历史记录 */ private void loadHistory() { - File file = new File(HISTORY_FILE); + File file = HISTORY_FILE.toFile(); if (!file.exists()) { return; } try { - String jsonString = Files.readString(Paths.get(HISTORY_FILE), StandardCharsets.UTF_8); + String jsonString = Files.readString(HISTORY_FILE, StandardCharsets.UTF_8); if (jsonString.trim().isEmpty()) { return; } diff --git a/src/main/java/com/laker/postman/service/WorkspaceService.java b/src/main/java/com/laker/postman/service/WorkspaceService.java index 096883ce..0be432b1 100644 --- a/src/main/java/com/laker/postman/service/WorkspaceService.java +++ b/src/main/java/com/laker/postman/service/WorkspaceService.java @@ -81,7 +81,7 @@ public void createWorkspace(Workspace workspace) throws Exception { // 对于非Git克隆模式,创建本地目录 if (workspace.getType() != WorkspaceType.GIT || workspace.getGitRepoSource() != GitRepoSource.CLONED) { - Path workspacePath = Paths.get(workspace.getPath()); + Path workspacePath = workspace.getPath(); if (!Files.exists(workspacePath)) { Files.createDirectories(workspacePath); } @@ -144,7 +144,7 @@ public SshCredentialsProvider getSshCredentialsProvider(Workspace workspace) { private void cloneRepository(Workspace workspace) throws Exception { CloneCommand cloneCommand = Git.cloneRepository() .setURI(workspace.getGitRemoteUrl()) - .setDirectory(new File(workspace.getPath())); + .setDirectory(workspace.getPath().toFile()); cloneCommand.setTimeout(GIT_OPERATION_TIMEOUT); // 设置超时时间 // 如果用户指定了特定的分支,设置分支名称 @@ -204,7 +204,7 @@ private void cloneRepository(Workspace workspace) throws Exception { * 初始化本地Git仓库 */ private void initializeGitRepository(Workspace workspace) throws Exception { - try (Git git = Git.init().setDirectory(new File(workspace.getPath())).call()) { + try (Git git = Git.init().setDirectory(workspace.getPath().toFile()).call()) { // 创建初始提交 createInitialCommit(git, workspace); @@ -242,7 +242,7 @@ private void initializeGitRepository(Workspace workspace) throws Exception { */ private void createInitialCommit(Git git, Workspace workspace) throws Exception { // 创建README文件 - Path readmePath = Paths.get(workspace.getPath(), "README.md"); + Path readmePath = workspace.getPath().resolve("README.md"); Files.write(readmePath, String.format("# %s\n\n%s", workspace.getName(), workspace.getDescription() != null ? workspace.getDescription() : "EasyPostman Workspace").getBytes()); @@ -287,7 +287,7 @@ private void validateWorkspace(Workspace workspace) throws IllegalArgumentExcept throw new IllegalArgumentException("Workspace name is required"); } - if (workspace.getPath() == null || workspace.getPath().trim().isEmpty()) { + if (workspace.getPath() == null) { throw new IllegalArgumentException("Workspace path is required"); } @@ -310,9 +310,9 @@ private void validateWorkspace(Workspace workspace) throws IllegalArgumentExcept } // 检查路径是否已被其他工作区使用 - String normalizedPath = Paths.get(workspace.getPath()).toAbsolutePath().normalize().toString(); + Path normalizedPath = workspace.getPath().toAbsolutePath().normalize(); boolean pathExists = workspaces.stream() - .anyMatch(w -> Paths.get(w.getPath()).toAbsolutePath().normalize().toString().equals(normalizedPath)); + .anyMatch(w -> w.getPath().toAbsolutePath().normalize().equals(normalizedPath)); if (pathExists) { throw new IllegalArgumentException("Path is already used by another workspace"); @@ -320,7 +320,7 @@ private void validateWorkspace(Workspace workspace) throws IllegalArgumentExcept // 对于Git克隆模式,检查目标目录是否已存在且不为空 if (workspace.getType() == WorkspaceType.GIT && workspace.getGitRepoSource() == GitRepoSource.CLONED) { - Path targetPath = Paths.get(workspace.getPath()); + Path targetPath = workspace.getPath(); if (Files.exists(targetPath)) { try { // 检查目录是否为空 @@ -363,7 +363,7 @@ public void deleteWorkspace(String workspaceId) throws Exception { throw new IllegalArgumentException("Default workspace cannot be deleted"); } // 删除工作区文件 - Path workspacePath = Paths.get(workspace.getPath()); + Path workspacePath = workspace.getPath(); if (Files.exists(workspacePath)) { deleteDirectoryRecursively(workspacePath); } @@ -450,7 +450,7 @@ public GitOperationResult pullUpdates(String workspaceId) throws Exception { throw new IllegalStateException("Not a Git workspace"); } - try (Git git = Git.open(new File(workspace.getPath()))) { + try (Git git = Git.open(workspace.getPath().toFile())) { String branch = git.getRepository().getBranch(); String tracking = git.getRepository().getConfig().getString("branch", branch, "merge"); log.info("Current branch: {}, tracking: {}", branch, tracking); @@ -626,7 +626,7 @@ public GitOperationResult pushChanges(String workspaceId) throws Exception { throw new IllegalStateException("Not a Git workspace"); } - try (Git git = Git.open(new File(workspace.getPath()))) { + try (Git git = Git.open(workspace.getPath().toFile())) { // 检查是否有远程仓库 var remotes = git.remoteList().call(); if (remotes.isEmpty()) { @@ -831,7 +831,7 @@ public GitOperationResult forcePushChanges(String workspaceId) throws Exception throw new IllegalStateException("Not a Git workspace"); } - try (Git git = Git.open(new File(workspace.getPath()))) { + try (Git git = Git.open(workspace.getPath().toFile())) { String currentBranch = git.getRepository().getBranch(); // 获取认证信息 @@ -891,7 +891,7 @@ public GitOperationResult stashChanges(String workspaceId) throws Exception { throw new IllegalStateException("Not a Git workspace"); } - try (Git git = Git.open(new File(workspace.getPath()))) { + try (Git git = Git.open(workspace.getPath().toFile())) { // 获取暂存前的状态 var status = git.status().call(); @@ -938,7 +938,7 @@ public GitOperationResult popStashChanges(String workspaceId) throws Exception { throw new IllegalStateException("Not a Git workspace"); } - try (Git git = Git.open(new File(workspace.getPath()))) { + try (Git git = Git.open(workspace.getPath().toFile())) { // 检查是否有暂存 var stashList = git.stashList().call(); if (!stashList.iterator().hasNext()) { @@ -980,7 +980,7 @@ public GitOperationResult forcePullUpdates(String workspaceId) throws Exception throw new IllegalStateException("Not a Git workspace"); } - try (Git git = Git.open(new File(workspace.getPath()))) { + try (Git git = Git.open(workspace.getPath().toFile())) { // 记录拉取前的未提交变更(将被丢弃) var statusBefore = git.status().call(); result.affectedFiles.addAll(statusBefore.getModified()); @@ -1044,7 +1044,7 @@ public GitOperationResult commitChanges(String workspaceId, String message) thro throw new IllegalStateException("Not a Git workspace"); } - try (Git git = Git.open(new File(workspace.getPath()))) { + try (Git git = Git.open(workspace.getPath().toFile())) { // 检查是否有文件需要提交 var status = git.status().call(); boolean hasChanges = !status.getAdded().isEmpty() || @@ -1115,7 +1115,7 @@ public GitOperationResult commitChanges(String workspaceId, String message) thro */ public List getChangedFilesBetweenCommits(String workspaceId, String oldCommitId, String newCommitId) throws Exception { Workspace workspace = getWorkspaceById(workspaceId); - try (Git git = Git.open(new File(workspace.getPath()))) { + try (Git git = Git.open(workspace.getPath().toFile())) { ObjectId oldId = git.getRepository().resolve(oldCommitId); ObjectId newId = git.getRepository().resolve(newCommitId); List diffs = git.diff() @@ -1210,7 +1210,7 @@ public void addRemoteRepository(String workspaceId, String remoteUrl, String rem throw new IllegalStateException("Only Git workspaces of type INITIALIZED can add a remote repository"); } - try (Git git = Git.open(new File(workspace.getPath()))) { + try (Git git = Git.open(workspace.getPath().toFile())) { // 添加远程仓库 git.remoteAdd() .setName("origin") @@ -1271,7 +1271,7 @@ public RemoteStatus getRemoteStatus(String workspaceId) throws Exception { throw new IllegalStateException("Not a Git workspace"); } - try (Git git = Git.open(new File(workspace.getPath()))) { + try (Git git = Git.open(workspace.getPath().toFile())) { RemoteStatus status = new RemoteStatus(); // 获取远程仓库列表 diff --git a/src/main/java/com/laker/postman/service/collections/OpenedRequestsService.java b/src/main/java/com/laker/postman/service/collections/OpenedRequestsService.java index dc4701f2..99c002bc 100644 --- a/src/main/java/com/laker/postman/service/collections/OpenedRequestsService.java +++ b/src/main/java/com/laker/postman/service/collections/OpenedRequestsService.java @@ -19,20 +19,21 @@ import java.awt.*; import java.io.File; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @Slf4j public class OpenedRequestsService { - public static final String PATHNAME = SystemUtil.getUserHomeEasyPostmanPath() + "opened_requests.json"; + public static final Path PATHNAME = SystemUtil.EASY_POSTMAN_HOME.resolve("opened_requests.json"); private OpenedRequestsService() { throw new IllegalStateException("Utility class"); } public static List getAll() { - File file = new File(PATHNAME); + File file = PATHNAME.toFile(); if (!file.exists()) { return List.of(); } @@ -119,7 +120,7 @@ public static void save() { // 保存所有到单独的 JSON 文件 if (!openedRequestItem.isEmpty()) { try { - File file = new File(PATHNAME); + File file = PATHNAME.toFile(); JSONArray arr = new JSONArray(); for (HttpRequestItem item : openedRequestItem) { arr.add(JSONUtil.parse(item)); @@ -133,7 +134,7 @@ public static void save() { } public static void clear() { - File file = new File(PATHNAME); + File file = PATHNAME.toFile(); if (file.exists()) { try { FileUtil.del(file); diff --git a/src/main/java/com/laker/postman/service/collections/RequestsPersistence.java b/src/main/java/com/laker/postman/service/collections/RequestsPersistence.java index 07bb69ea..581f25e6 100644 --- a/src/main/java/com/laker/postman/service/collections/RequestsPersistence.java +++ b/src/main/java/com/laker/postman/service/collections/RequestsPersistence.java @@ -10,17 +10,18 @@ import javax.swing.tree.DefaultTreeModel; import java.io.*; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Slf4j public class RequestsPersistence { - private String filePath; + private Path filePath; private final DefaultMutableTreeNode rootTreeNode; private final DefaultTreeModel treeModel; - public RequestsPersistence(String filePath, DefaultMutableTreeNode rootTreeNode, DefaultTreeModel treeModel) { + public RequestsPersistence(Path filePath, DefaultMutableTreeNode rootTreeNode, DefaultTreeModel treeModel) { this.filePath = filePath; this.rootTreeNode = rootTreeNode; this.treeModel = treeModel; @@ -38,7 +39,7 @@ public void exportRequestCollection(File fileToSave) throws IOException { } public void initRequestGroupsFromFile() { - File file = new File(filePath); + File file = filePath.toFile(); if (!file.exists()) { // 如果文件不存在,则创建默认请求组 RequestsFactory.createDefaultRequestGroups(rootTreeNode, treeModel); // 创建默认请求组 saveRequestGroups(); // 保存默认请求组到文件 @@ -63,7 +64,7 @@ public void initRequestGroupsFromFile() { } public void saveRequestGroups() { - try (Writer writer = new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8)) { + try (Writer writer = new OutputStreamWriter(new FileOutputStream(filePath.toFile()), StandardCharsets.UTF_8)) { JSONArray array = new JSONArray(); for (int i = 0; i < rootTreeNode.getChildCount(); i++) { DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) rootTreeNode.getChildAt(i); @@ -133,8 +134,8 @@ public JSONObject buildGroupJson(DefaultMutableTreeNode node) { /** * 切换数据文件路径并重新加载集合 */ - public void setDataFilePath(String path) { - if (path == null || path.isBlank()) return; + public void setDataFilePath(Path path) { + if (path == null) return; this.filePath = path; // 清空现有树 rootTreeNode.removeAllChildren(); diff --git a/src/main/java/com/laker/postman/service/git/GitConflictDetector.java b/src/main/java/com/laker/postman/service/git/GitConflictDetector.java index 8867ad8f..8257aa7d 100644 --- a/src/main/java/com/laker/postman/service/git/GitConflictDetector.java +++ b/src/main/java/com/laker/postman/service/git/GitConflictDetector.java @@ -29,6 +29,7 @@ import java.io.File; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -53,12 +54,12 @@ private GitConflictDetector() { /** * 检查Git仓库状态,判断是否可以执行指定操作 */ - public static GitStatusCheck checkGitStatus(String workspacePath, String operationType, + public static GitStatusCheck checkGitStatus(Path workspacePath, String operationType, CredentialsProvider credentialsProvider, SshCredentialsProvider sshCredentialsProvider) { GitStatusCheck result = new GitStatusCheck(); - try (Git git = Git.open(new File(workspacePath))) { + try (Git git = Git.open(workspacePath.toFile())) { // 获取基本信息 result.currentBranch = git.getRepository().getBranch(); @@ -100,7 +101,7 @@ private static void checkLocalStatus(Status status, GitStatusCheck result) { result.canCommit = totalChanges > 0 && result.conflicting.isEmpty(); } - private static void checkRemoteStatus(Git git, String workspacePath, GitStatusCheck result, + private static void checkRemoteStatus(Git git, Path workspacePath, GitStatusCheck result, CredentialsProvider credentialsProvider, SshCredentialsProvider sshCredentialsProvider) { try { @@ -707,7 +708,7 @@ private static void generatePullSuggestions(GitStatusCheck result) { * 执行冲突检测 * 通过分析本地和远程的变更,判断是否存在实际冲突以及是否可以自动合并 */ - private static void performIntelligentConflictDetection(Git git, String workspacePath, GitStatusCheck result, ObjectId localId, ObjectId remoteId) { + private static void performIntelligentConflictDetection(Git git, Path workspacePath, GitStatusCheck result, ObjectId localId, ObjectId remoteId) { try { // 如果本地或远程仓库为空,则无法进行智能冲突检测 if (localId == null || remoteId == null) { @@ -776,7 +777,7 @@ private static ObjectId findMergeBase(Git git, ObjectId commit1, ObjectId commit /** * 分析文件级别的冲突 */ - private static void analyzeFileConflicts(Git git, String workspacePath, GitStatusCheck result, ObjectId mergeBase, + private static void analyzeFileConflicts(Git git, Path workspacePath, GitStatusCheck result, ObjectId mergeBase, ObjectId localId, ObjectId remoteId) { try { // 获取从merge base到本地的变更 diff --git a/src/main/java/com/laker/postman/util/SystemUtil.java b/src/main/java/com/laker/postman/util/SystemUtil.java index 8a37e660..d5b8f090 100644 --- a/src/main/java/com/laker/postman/util/SystemUtil.java +++ b/src/main/java/com/laker/postman/util/SystemUtil.java @@ -15,13 +15,13 @@ @Slf4j public class SystemUtil { - public static final String LOG_DIR = getUserHomeEasyPostmanPath() + "logs" + File.separator; - private static final String COLLECTION_PATH = getUserHomeEasyPostmanPath() + "collections.json"; - private static final String ENV_PATH = getUserHomeEasyPostmanPath() + "environments.json"; - - public static String getUserHomeEasyPostmanPath() { - return System.getProperty("user.home") + File.separator + "EasyPostman" + File.separator; - } + public static final Path EASY_POSTMAN_HOME = Paths.get( + System.getProperty("user.home"), + "EasyPostman" + ).toAbsolutePath(); + public static final Path LOG_DIR = EASY_POSTMAN_HOME.resolve("logs"); + private static final Path COLLECTION_PATH = EASY_POSTMAN_HOME.resolve("collections.json"); + private static final Path ENV_PATH = EASY_POSTMAN_HOME.resolve("environments.json"); /** * 获取当前版本号:优先从 MANIFEST.MF Implementation-Version,若无则尝试读取 pom.xml @@ -76,17 +76,17 @@ public static String getClipboardCurlText() { return null; } - public static String getEnvPathForWorkspace(Workspace ws) { + public static Path getEnvPathForWorkspace(Workspace ws) { if (ws == null) { return ENV_PATH; } - return ws.getPath() + File.separator + "environments.json"; + return ws.getPath().resolve("environments.json"); } - public static String getCollectionPathForWorkspace(Workspace ws) { + public static Path getCollectionPathForWorkspace(Workspace ws) { if (ws == null) { return COLLECTION_PATH; } - return ws.getPath() + File.separator + "collections.json"; + return ws.getPath().resolve("collections.json"); } } \ No newline at end of file diff --git a/src/main/java/com/laker/postman/util/UserSettingsUtil.java b/src/main/java/com/laker/postman/util/UserSettingsUtil.java index 3dfd5a1d..cbb2adf3 100644 --- a/src/main/java/com/laker/postman/util/UserSettingsUtil.java +++ b/src/main/java/com/laker/postman/util/UserSettingsUtil.java @@ -6,6 +6,7 @@ import java.io.File; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -16,7 +17,7 @@ public class UserSettingsUtil { private static final String KEY_WINDOW_HEIGHT = "windowHeight"; private static final String KEY_WINDOW_MAXIMIZED = "windowMaximized"; private static final String KEY_LANGUAGE = "language"; - private static final String SETTINGS_PATH = SystemUtil.getUserHomeEasyPostmanPath() + "user_settings.json"; + private static final Path SETTINGS_PATH = SystemUtil.EASY_POSTMAN_HOME.resolve("user_settings.json"); private static final Object lock = new Object(); private static Map settingsCache = null; @@ -27,7 +28,7 @@ private UserSettingsUtil() { private static Map readSettings() { synchronized (lock) { if (settingsCache != null) return settingsCache; - File file = new File(SETTINGS_PATH); + File file = SETTINGS_PATH.toFile(); if (!file.exists()) { settingsCache = new HashMap<>(); return settingsCache; @@ -51,7 +52,7 @@ private static void saveSettings() { synchronized (lock) { try { String json = JSONUtil.toJsonPrettyStr(settingsCache); - FileUtil.writeString(json, new File(SETTINGS_PATH), StandardCharsets.UTF_8); + FileUtil.writeString(json, SETTINGS_PATH.toFile(), StandardCharsets.UTF_8); } catch (Exception e) { log.warn("保存用户设置失败", e); } diff --git a/src/main/java/com/laker/postman/util/WorkspaceStorageUtil.java b/src/main/java/com/laker/postman/util/WorkspaceStorageUtil.java index b460b301..779f48f4 100644 --- a/src/main/java/com/laker/postman/util/WorkspaceStorageUtil.java +++ b/src/main/java/com/laker/postman/util/WorkspaceStorageUtil.java @@ -8,6 +8,7 @@ import java.io.File; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -22,8 +23,8 @@ public class WorkspaceStorageUtil { private static final String WORKSPACES_FILE = "workspaces.json"; private static final String WORKSPACE_SETTINGS_FILE = "workspace_settings.json"; - private static final String WORKSPACES_PATH = SystemUtil.getUserHomeEasyPostmanPath() + WORKSPACES_FILE; - private static final String WORKSPACE_SETTINGS_PATH = SystemUtil.getUserHomeEasyPostmanPath() + WORKSPACE_SETTINGS_FILE; + private static final Path WORKSPACES_PATH = SystemUtil.EASY_POSTMAN_HOME.resolve(WORKSPACES_FILE); + private static final Path WORKSPACE_SETTINGS_PATH = SystemUtil.EASY_POSTMAN_HOME.resolve(WORKSPACE_SETTINGS_FILE); private static final Object lock = new Object(); private static final String DEFAULT_WORKSPACE_ID = "default-workspace"; @@ -49,7 +50,7 @@ public static Workspace getDefaultWorkspace() { ws.setId(DEFAULT_WORKSPACE_ID); ws.setName(DEFAULT_WORKSPACE_NAME); ws.setType(WorkspaceType.LOCAL); - ws.setPath(SystemUtil.getUserHomeEasyPostmanPath()); + ws.setPath(SystemUtil.EASY_POSTMAN_HOME); ws.setDescription(DEFAULT_WORKSPACE_DESCRIPTION); ws.setCreatedAt(System.currentTimeMillis()); ws.setUpdatedAt(System.currentTimeMillis()); @@ -63,7 +64,7 @@ public static void saveWorkspaces(List workspaces) { synchronized (lock) { try { // 确保目录存在 - File file = new File(WORKSPACES_PATH); + File file = WORKSPACES_PATH.toFile(); FileUtil.mkParentDirs(file); // 保证默认工作区始终存在 boolean hasDefault = workspaces.stream().anyMatch(WorkspaceStorageUtil::isDefaultWorkspace); @@ -86,7 +87,7 @@ public static void saveWorkspaces(List workspaces) { public static List loadWorkspaces() { synchronized (lock) { try { - File file = new File(WORKSPACES_PATH); + File file = WORKSPACES_PATH.toFile(); List workspaces; if (!file.exists()) { log.debug("Workspaces file not found, returning default workspace"); @@ -123,7 +124,7 @@ public static List loadWorkspaces() { public static void saveCurrentWorkspace(String workspaceId) { synchronized (lock) { try { - File file = new File(WORKSPACE_SETTINGS_PATH); + File file = WORKSPACE_SETTINGS_PATH.toFile(); FileUtil.mkParentDirs(file); Map settings = loadWorkspaceSettings(); @@ -159,7 +160,7 @@ public static String getCurrentWorkspace() { */ private static Map loadWorkspaceSettings() { try { - File file = new File(WORKSPACE_SETTINGS_PATH); + File file = WORKSPACE_SETTINGS_PATH.toFile(); if (!file.exists()) { return new HashMap<>(); }