Skip to content

feat(common): Add HttpTool #2142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 11, 2025
Merged

feat(common): Add HttpTool #2142

merged 9 commits into from
May 11, 2025

Conversation

unknowIfGuestInDream
Copy link
Owner

@unknowIfGuestInDream unknowIfGuestInDream commented May 10, 2025

Fixes #1007

Proposed Changes

  1. ...
  2. ...
  3. ...

Readiness Checklist

Author/Contributor

  • If documentation is needed for this change, has that been included in this pull request

Reviewing Maintainer

  • Label as either enhancement, bug, documentation or dependencies
  • Verify design and implementation

Summary by Sourcery

Add HTTP debugging tool and enhance HTTP utility classes with comprehensive HTTP method support and JSON handling

New Features:

  • Introduce HttpTool for HTTP request debugging
  • Add JSON formatting and compaction utilities
  • Implement comprehensive HTTP method support in HttpUtil

Enhancements:

  • Improve HttpUtil to support GET, POST, PUT, PATCH, DELETE, and HEAD methods
  • Add dynamic User-Agent selection based on operating system
  • Enhance JacksonUtil with JSON formatting methods

Tests:

  • Add support for various HTTP request types
  • Implement JSON parsing and formatting capabilities

Summary by CodeRabbit

  • 新功能
    • 新增 HTTP 调试工具,支持通过图形界面自定义请求方法(GET、POST、PUT、PATCH、DELETE、HEAD)、参数、Header、Cookie,并可切换原始字符串与键值对输入。
    • 新增 JSON 语法高亮编辑器,支持实时高亮、格式化与压缩 JSON 内容。
    • HTTP 工具支持显示响应头、响应体及图片响应,提升调试体验。
    • 新增快捷操作按钮,可直接在系统默认浏览器打开请求 URL。
    • 新增 JSON 语法高亮专用 CSS 样式,优化 JSON 展示效果。
    • 新增用于检查 RichTextFX 依赖的工具方法。
    • 新增文本区域替换全文内容方法,提升文本操作便捷性。
  • 优化
    • HTTP 请求工具自动根据操作系统动态设置 User-Agent,提升兼容性。
    • HTTP 请求方法扩展支持 PUT、DELETE、PATCH、HEAD,增强请求能力。
    • 调整日志级别,减少无关警告信息。
  • 依赖变更
    • 增加 jdk.httpserver 和 org.fxmisc.flowless 模块依赖。
  • 修正
    • 修正中文注释错别字,提升代码注释准确性。

Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
Copy link

Thank you for following naming conventions! 😻

Copy link

sourcery-ai bot commented May 10, 2025

Reviewer's Guide

This PR introduces HttpTool, a JavaFX-based HTTP debugging utility. Implementation involved creating its FXML-defined UI, logic for various HTTP methods and parameters, and response visualization. Supporting this, HttpUtil was enhanced with new methods and HttpResponse<String> return types, JacksonUtil gained JSON formatting/compacting functions, and JsonCodeArea was added for syntax-highlighted JSON. Module dependencies org.fxmisc.flowless (for JsonCodeArea) and jdk.httpserver were also added.

File-Level Changes

Change Details Files
Implemented the HttpTool JavaFX application for debugging HTTP requests.
  • Created UI for request configuration (URL, method, headers, body) and response display.
  • Added logic to handle GET, POST, PUT, DELETE, PATCH, HEAD methods.
  • Enabled request body input as key-value pairs or raw string.
  • Added tool icon and jdk.httpserver module dependency.
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java
common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml
core/src/main/java/com/tlcsdm/core/javafx/helper/ImageViewHelper.java
common/src/main/java/module-info.java
Enhanced HttpUtil for broader HTTP method support and detailed responses.
  • Added doPut, doDelete, doPatch, doHead methods.
  • Standardized method return types to HttpResponse<String>.
  • Updated User-Agent header generation to be OS-dependent.
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java
Introduced JSON processing utilities and a syntax-highlighting JsonCodeArea.
  • Added formatJson and compactJson methods to JacksonUtil.
  • Developed JsonCodeArea for styled JSON display using RichTextFX.
  • Added org.fxmisc.flowless module dependency for JsonCodeArea.
core/src/main/java/com/tlcsdm/core/util/JacksonUtil.java
core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css
common/src/main/java/module-info.java
Minor code refinements in existing utilities.
  • Adjusted method visibility in ScanPortTool.
  • Updated logging level in FxJDKToolActionGroup.
common/src/main/java/com/tlcsdm/jfxcommon/debug/ScanPortTool.java
core/src/main/java/com/tlcsdm/core/javafx/controlsfx/FxJDKToolActionGroup.java

Assessment against linked issues

Issue Objective Addressed Explanation
#1007 Implement an HTTP testing tool within the application.
#1007 Provide support for common HTTP methods (GET, POST, HEAD, PUT, PATCH, DELETE).
#1007 Allow users to set request parameters, headers, and cookies.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

vercel bot commented May 10, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
javafx-tool ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 11, 2025 2:46am

Copy link

quine-bot bot commented May 10, 2025

👋 Figuring out if a PR is useful is hard, hopefully this will help.

  • @unknowIfGuestInDream has been on GitHub since 2019 and in that time has had 1241 public PRs merged
  • Don't you recognize them? They've been here before 🎉
  • Here's a good example of their work: javafxTool (Javafx scaffolding, built on JDK17 + JavaFX21 + controlsfx 11.x.x + Maven)
  • From looking at their profile, they seem to be good with Java and HTML.

Their most recently public accepted PR is: #2134

Copy link

coderabbitai bot commented May 10, 2025

Warning

Rate limit exceeded

@unknowIfGuestInDream has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 51 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 111c038 and 0cd1d1d.

📒 Files selected for processing (1)
  • common/src/main/java/module-info.java (1 hunks)

"""

Walkthrough

本次变更主要新增了一个基于JavaFX的HTTP接口调试工具,包括前端FXML界面和后端逻辑实现,支持多种HTTP方法、参数、Header和Cookie配置,并能显示响应内容和头部信息。同时,扩展了底层HTTP工具类,支持更多HTTP请求方式,并增加了JSON格式化与压缩等实用方法。相关依赖和资源文件也已同步更新。

Changes

文件或分组 变更摘要
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java
common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml
新增HTTP调试工具的Java类和FXML界面,实现完整的HTTP请求构建、发送与响应展示功能。
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java 扩展支持PUT、DELETE、PATCH、HEAD等HTTP方法,返回类型改为HttpResponse,优化Header构建逻辑。
core/src/main/java/com/tlcsdm/core/util/JacksonUtil.java 新增formatJson和compactJson静态方法,实现JSON格式化和压缩。
core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css
新增JSON高亮编辑器组件及其样式文件,支持JSON语法高亮显示。
common/src/main/java/module-info.java 增加org.fxmisc.flowless模块依赖。
core/src/main/java/com/tlcsdm/core/javafx/helper/ImageViewHelper.java 新增“http”图标资源路径支持。
common/src/main/java/com/tlcsdm/jfxcommon/debug/ScanPortTool.java 将setTableColumnMapValueFactory方法访问修饰符由public改为private。
core/src/main/java/com/tlcsdm/core/javafx/controlsfx/FxJDKToolActionGroup.java 调整日志级别,将JDK工具未找到的日志从warn降为debug。
core/src/main/java/com/tlcsdm/core/javafx/richtext/InformationArea.java 新增setText方法支持文本替换。
core/src/main/java/com/tlcsdm/core/util/DependencyUtil.java 修正注释错别字,新增hasRichTextFX方法检测RichTextFX依赖。

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant HttpTool(UI)
    participant HttpUtil
    participant RemoteServer

    User->>HttpTool(UI): 输入URL、选择方法、配置参数
    User->>HttpTool(UI): 点击“发送”
    HttpTool(UI)->>HttpUtil: 构建并发送HTTP请求
    HttpUtil->>RemoteServer: HTTP请求
    RemoteServer-->>HttpUtil: HTTP响应
    HttpUtil-->>HttpTool(UI): 返回HttpResponse
    HttpTool(UI)-->>User: 展示响应内容与头部信息
Loading

Assessment against linked issues

Objective Addressed Explanation
创建HTTP接口测试工具类并提供界面与功能(#1007
扩展HttpUtil支持多种HTTP方法及返回HttpResponse(#1007
新增JSON格式化/压缩功能及相关UI支持(#1007
增加相关依赖与资源文件,保证工具完整性(#1007

Suggested labels

test, dependency-submission, i18ns

Suggested reviewers

  • DreamAwakenFateBroke

Poem

兔子调试HTTP,界面焕然新,
请求方法全,参数自定义。
响应展示明,JSON高亮新,
格式随心变,代码更清新。
新工具上线,兔子乐开怀! 🐰🌐
"""

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@mergify mergify bot added the enhancement New feature or request label May 10, 2025
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @unknowIfGuestInDream - I've reviewed your changes - here's some feedback:

  • HttpUtil.execute returning null on exceptions can hide the root cause of errors from HttpTool.
  • HttpTool should explicitly set Content-Type for requests with bodies, as HttpUtil no longer defaults it.
  • Clarify the purpose of new dependencies org.fxmisc.flowless (for JsonCodeArea) and jdk.httpserver, as their usage by HttpTool is not apparent from the diff.
Here's what I looked at during the review
  • 🟡 General issues: 3 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Contributor

github-actions bot commented May 10, 2025

Qodana Community for JVM

It seems all right 👌

No new problems were found according to the checks applied

💡 Qodana analysis was run in the pull request mode: only the changed files were checked
☁️ View the detailed Qodana report

Contact Qodana team

Contact us at qodana-support@jetbrains.com

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🔭 Outside diff range comments (2)
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (2)

128-144: ⚠️ Potential issue

默认 UA 覆盖用户自定义 Header,违反最小惊讶原则

buildHeader 先写入调用方提供的 Header,随后无条件 builder.setHeader("User-Agent", userAgent),会覆盖掉调用方显式设置的 UA。建议:

-if (header != null && !header.containsKey("User-Agent")) {
-    builder.setHeader("User-Agent", userAgent);
-}
+builder.headers().map(); // no-op, just to illustrate

或者在循环前先设置默认 UA,循环时使用 builder.header(key, value) 追加而非覆盖。


107-125: 🛠️ Refactor suggestion

表单编码遗漏 URLEncoder,且尾随 tmp=tmp 令人生疑

  1. 拼装 k=v 时未对 k、v 进行 URL 编码。
  2. 结尾追加 tmp=tmp 会向服务器发送无效字段,建议删除。
🧹 Nitpick comments (9)
common/src/main/java/module-info.java (1)

57-58: 模块依赖添加合理

添加jdk.httpserverorg.fxmisc.flowless依赖是支持新增的HTTP调试工具所必需的。HTTP服务器模块用于测试功能,flowless模块用于高级UI控件支持。

可以考虑将这些依赖标记为静态依赖(如requires static),如果它们只在特定功能使用时才需要。

-    requires jdk.httpserver;
-    requires org.fxmisc.flowless;
+    requires static jdk.httpserver;
+    requires static org.fxmisc.flowless;
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (1)

1-42: JSON语法高亮样式表设计良好

CSS文件定义了JSON语法高亮的样式,为不同的JSON元素(键、值、括号、逗号等)设置了不同的颜色,使JSON内容在UI中更易于阅读和理解。

关于静态分析工具的警告:-fx-fill 属性在JavaFX CSS中是有效的,用于设置文本颜色。这些警告是误报,可以安全忽略。

可以考虑添加一些注释说明每种颜色的设计意图,以及可能的暗色主题适配方案。

🧰 Tools
🪛 Biome (1.9.4)

[error] 29-29: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 33-33: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 37-37: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)

common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml (1)

1-179: 布局结构清晰,功能完整的HTTP工具UI

FXML文件定义了一个功能完善的HTTP调试工具界面,包括:

  1. 顶部的URL输入和HTTP方法选择
  2. 左侧的请求参数、请求头和Cookie配置
  3. 中间区域的响应内容、响应头和图像显示

布局组织良好,ID命名规范,为控制器类提供了清晰的引用点。

建议考虑以下几点改进:

  1. 添加国际化支持,替换硬编码的中文文本
  2. 考虑为响应区域添加状态代码和响应时间的显示
  3. 可能需要添加一个请求体(body)编辑区域,支持POST、PUT等方法
core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java (2)

40-44: 修复JavaDoc中的拼写错误

类注释中有一个拼写错误:"SON Code Area",应该是"JSON Code Area"。

-/**
- * SON Code Area
- *
- * @author unknowIfGuestInDream
- */
+/**
+ * JSON Code Area
+ *
+ * @author unknowIfGuestInDream
+ */

76-94: 高亮计算方法实现高效

computeHighlighting方法使用正则表达式匹配器和StyleSpansBuilder有效地计算并应用样式跨度。代码逻辑清晰,使用了适当的断言确保样式类不为空。

可以考虑添加性能优化,对于大型JSON文档,可能需要限制单次处理的文本长度或采用增量处理方法。

common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (3)

300-304: 仅将 200 视为成功过于严格

HTTP 201、202、204、3xx(重定向) 等状态也可能代表正常流程。建议改为 >=200 && <400 或让用户决定是否接受重定向/无内容响应。


244-252: 为空 Cookie 仍然插入 Header,可省略

paramsCookietableData 为空,仍然向 headerMap 写入 Cookie: "",可能导致服务器解析异常。可在 !paramsCookieBuffer.isEmpty() 时再执行 headerMap.put(...)


105-110: 常量应声明为 static final 提升可读性

methodStringsparamsDatatableData 等不随实例变化,建议:

-private String[] methodStrings = new String[]{"GET", "POST", "HEAD", "PUT", "PATCH", "DELETE"};
+private static final String[] METHOD_STRINGS = {"GET", "POST", "HEAD", "PUT", "PATCH", "DELETE"};

同时修改引用。

core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (1)

146-151: 每次请求都创建 HttpClient,浪费资源并导致连接复用失效

HttpClient 线程安全且支持 keep-alive,建议改为单例:

-private static HttpResponse<String> execute(HttpRequest.Builder builder, Charset charset) {
-    var request = builder.build();
-    try {
-        var client = HttpClient.newBuilder().sslContext(SSLContextBuilder.create().build()).build();
+private static final HttpClient CLIENT =
+    HttpClient.newBuilder()
+        .sslContext(SSLContextBuilder.create().build())
+        .build();
+
+private static HttpResponse<String> execute(HttpRequest.Builder builder, Charset charset) {
+    var request = builder.build();
+    try {
+        var client = CLIENT;
         return client.send(request, HttpResponse.BodyHandlers.ofString(charset));

可进一步设置全局超时、重定向策略等。

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 944d9f1 and eceefde.

⛔ Files ignored due to path filters (2)
  • core/src/main/resources/com/tlcsdm/core/static/icon/http.png is excluded by !**/*.png
  • core/src/main/resources/com/tlcsdm/core/static/icon/http@2x.png is excluded by !**/*.png
📒 Files selected for processing (10)
  • common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (1 hunks)
  • common/src/main/java/com/tlcsdm/jfxcommon/debug/ScanPortTool.java (1 hunks)
  • common/src/main/java/module-info.java (1 hunks)
  • common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml (1 hunks)
  • core/src/main/java/com/tlcsdm/core/javafx/controlsfx/FxJDKToolActionGroup.java (1 hunks)
  • core/src/main/java/com/tlcsdm/core/javafx/helper/ImageViewHelper.java (1 hunks)
  • core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java (1 hunks)
  • core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (4 hunks)
  • core/src/main/java/com/tlcsdm/core/util/JacksonUtil.java (2 hunks)
  • core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (1)
core/src/main/java/com/tlcsdm/core/javafx/util/OSUtil.java (1)
  • OSUtil (46-185)
🪛 Biome (1.9.4)
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css

[error] 29-29: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 33-33: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 37-37: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)

🪛 GitHub Check: CodeFactor
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java

[notice] 223-316: common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java#L223-L316
Complex Method

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build (21, ubuntu-latest, false)
  • GitHub Check: build (17, windows-latest, false)
  • GitHub Check: build (21, windows-latest, false)
  • GitHub Check: build (21, macos-latest, false)
  • GitHub Check: build (17, ubuntu-latest, false)
  • GitHub Check: build (17, macos-latest, false)
  • GitHub Check: qodana
  • GitHub Check: StepSecurity Harden-Runner
  • GitHub Check: Summary
🔇 Additional comments (6)
core/src/main/java/com/tlcsdm/core/javafx/controlsfx/FxJDKToolActionGroup.java (1)

99-99: 日志级别调整得当

将未找到JDK工具可执行文件的日志级别从warn调整为debug是合理的改动,因为这种情况通常不是错误,而是配置差异导致的正常情况。

core/src/main/java/com/tlcsdm/core/util/JacksonUtil.java (1)

192-206: JSON格式化方法实现合理

该方法通过Jackson将JSON解析后重新格式化输出,实现了JSON美化功能。错误处理适当,在解析失败时返回原始字符串。

core/src/main/java/com/tlcsdm/core/javafx/helper/ImageViewHelper.java (1)

83-83: 图标资源添加符合需求

为HttpTool添加http图标支持,保持了代码一致性,与新功能匹配。

common/src/main/java/com/tlcsdm/jfxcommon/debug/ScanPortTool.java (1)

341-353: 良好的封装改进!

setTableColumnMapValueFactory 方法从 public 修改为 private 是一个很好的封装改进。这个方法只在类内部使用(在 initializeOption 方法中),限制其访问范围有助于隐藏实现细节,减少类的公共 API 暴露面。这符合面向对象设计中的信息隐藏原则。

core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java (1)

65-74: 构造函数实现完善

构造函数设置了适当的样式类和样式表,并添加了行号显示和文本变化监听器,以便在文本变化时更新语法高亮。这是一个良好的实现,确保了JSON编辑器的核心功能。

core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (1)

70-93: 新增 PUT/PATCH 请求体的 Content-Type 未明确

doPut/doPatch 接收字符串 body,但未设置 Content-Type,服务器可能无法正确解析。可与 doPostForm 类似增加参数或默认值(如 application/jsonapplication/x-www-form-urlencoded)。

Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (4)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (4)

260-273: ⚠️ Potential issue

GET请求参数未进行URL编码

直接拼接参数可能导致特殊字符(如空格、&、=、中文等)产生错误的URL。建议对参数名和值进行URL编码。

- paramsMap.forEach((key, value) -> paramsDataBuffer.append(key).append("=").append(value).append("&"));
+ paramsMap.forEach((key, value) -> {
+     try {
+         paramsDataBuffer.append(URLEncoder.encode(key, StandardCharsets.UTF_8.toString()))
+             .append("=")
+             .append(URLEncoder.encode(value, StandardCharsets.UTF_8.toString()))
+             .append("&");
+     } catch (UnsupportedEncodingException e) {
+         StaticLog.error(e, "URL编码错误");
+         paramsDataBuffer.append(key).append("=").append(value).append("&");
+     }
+ });

并添加相应的导入语句:

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.net.URLEncoder;

282-291: ⚠️ Potential issue

POST请求参数未进行URL编码

与GET请求类似,POST请求体的参数也需要进行URL编码,特别是在使用表单格式(application/x-www-form-urlencoded)时。

建议添加辅助方法进行参数编码,如:

private String encodeParameters(String input) {
    if (input == null || input.isEmpty()) {
        return input;
    }
    StringBuilder result = new StringBuilder();
    String[] params = input.split("&");
    for (String param : params) {
        int idx = param.indexOf("=");
        if (idx > 0) {
            String key = param.substring(0, idx);
            String value = param.substring(idx + 1);
            try {
                String encodedValue = URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
                result.append(key).append("=").append(encodedValue).append("&");
            } catch (Exception e) {
                // 异常情况下使用原始值
                result.append(param).append("&");
            }
        } else {
            result.append(param).append("&");
        }
    }
    if (result.length() > 0) {
        result.setLength(result.length() - 1);
    }
    return result.toString();
}

然后修改POST请求部分:

- response = HttpUtil.doPost(url, headerMap, body);
+ response = HttpUtil.doPost(url, headerMap, encodeParameters(body));

227-326: 🛠️ Refactor suggestion

方法体过长且职责过多

当前sendAction方法超过100行,包含多种职责(输入校验、请求构建、网络请求、响应处理等),可维护性差且难以测试。

建议拆分为多个职责单一的方法:

  1. validateInput() - 负责验证用户输入
  2. buildRequestParams() - 构建请求参数、头部和Cookie
  3. executeRequest() - 根据HTTP方法执行请求
  4. processResponse() - 处理响应并更新UI

例如:

@FXML
private void sendAction(ActionEvent event) {
    String url = urlTextField.getText().trim();
    if (!validateInput(url)) {
        return;
    }
    
    RequestParams params = buildRequestParams();
    executeRequestAsync(url, params);
}

private boolean validateInput(String url) {
    if (StringUtils.isEmpty(url)) {
        notificationBuilder.text("请输入网站!!!");
        notificationBuilder.showWarning();
        return false;
    }
    return true;
}

private RequestParams buildRequestParams() {
    // 构建参数、头部和Cookie的代码...
}

private void executeRequestAsync(String url, RequestParams params) {
    // 使用后台线程执行请求
    new Thread(() -> {
        HttpResponse<String> response = null;
        try {
            response = executeRequest(url, params);
            Platform.runLater(() -> processResponse(response));
        } catch (Exception e) {
            Platform.runLater(() -> {
                notificationBuilder.text("请求失败: " + e.getMessage());
                notificationBuilder.showError();
            });
        }
    }).start();
}
🧰 Tools
🪛 GitHub Check: CodeFactor

[notice] 227-326: common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java#L227-L326
Complex Method


260-301: 🛠️ Refactor suggestion

网络请求阻塞UI线程

当前直接在JavaFX Application Thread上执行HTTP请求,这会导致界面在请求期间冻结,影响用户体验。

建议使用异步方式执行请求:

// 使用CompletableFuture或Task
CompletableFuture.supplyAsync(() -> {
    // 执行HTTP请求...
    return HttpUtil.doGet(url, headerMap);
}).whenComplete((response, exception) -> {
    Platform.runLater(() -> {
        if (exception != null) {
            notificationBuilder.text("请求失败: " + exception.getMessage());
            notificationBuilder.showError();
        } else {
            // 处理响应...
            processResponse(response);
        }
    });
});

或者使用JavaFX的Task类:

Task<HttpResponse<String>> task = new Task<>() {
    @Override
    protected HttpResponse<String> call() throws Exception {
        return HttpUtil.doGet(url, headerMap);
    }
};

task.setOnSucceeded(e -> {
    HttpResponse<String> response = task.getValue();
    processResponse(response);
});

task.setOnFailed(e -> {
    notificationBuilder.text("请求失败: " + task.getException().getMessage());
    notificationBuilder.showError();
});

new Thread(task).start();
🧹 Nitpick comments (8)
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (1)

1-26: 许可证和版权信息

代码中的许可证日期(2025年)似乎是未来日期,可能需要更新为当前年份。

-/*
- * Copyright (c) 2025 unknowIfGuestInDream.
- * All rights reserved.
+/*
+ * Copyright (c) 2023 unknowIfGuestInDream.
+ * All rights reserved.
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (7)

192-203: 使用匿名内部类实现监听器

当前代码使用了匿名内部类实现ChangeListener,可以使用Lambda表达式简化代码。

- paramsDataIsStringCheckBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
-     @Override
-     public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
-         if (newValue) {
-             paramsDataTextArea.setVisible(true);
-             paramsDataTableView.setVisible(false);
-         } else {
-             paramsDataTextArea.setVisible(false);
-             paramsDataTableView.setVisible(true);
-         }
-     }
- });
+ paramsDataIsStringCheckBox.selectedProperty().addListener((observable, oldValue, newValue) -> {
+     paramsDataTextArea.setVisible(newValue);
+     paramsDataTableView.setVisible(!newValue);
+ });

92-96: 组件命名不一致

ResponseBodyTextAreaResponseHeaderTextArea组件使用了大写驼峰命名,而其他组件如urlTextField使用小写驼峰命名。应当保持一致的命名风格。

- @FXML
- private JsonCodeArea ResponseBodyTextArea;
- @FXML
- private InformationArea ResponseHeaderTextArea;
+ @FXML
+ private JsonCodeArea responseBodyTextArea;
+ @FXML
+ private InformationArea responseHeaderTextArea;

同时需要更新所有引用这些组件的地方,如第210、216、223、320、324行。


345-347: toBrowerAction方法中缺少错误提示

当URL为空时,该方法静默返回,没有向用户提供反馈。应该添加警告通知。

if (url.isEmpty()) {
+    notificationBuilder.text("请输入有效的URL");
+    notificationBuilder.showWarning();
    return;
}

351-354: 泛型类型安全性问题

setTableColumnMapValueFactory方法中的TableColumn参数缺少泛型类型声明,导致使用了原始类型,可能引起类型安全问题。

- private void setTableColumnMapValueFactory(TableColumn tableColumn, String name) {
+ private void setTableColumnMapValueFactory(TableColumn<Map<String, String>, String> tableColumn, String name) {

185-191: 未使用的注释代码

初始化UI方法中包含已注释掉的代码,这些代码可能是开发过程中的遗留物。应当移除这些无用代码以保持代码整洁。

- //        JsonCodeArea area = new JsonCodeArea();
- //        area.setEditable(false);
- //        area.appendText(
- //            FileUtil.readUtf8String(FileUtil.file(ConfigureUtil.getConfigurePath(Config.CONFIG_FILE_NAME))));
- //VirtualizedScrollPane<JsonCodeArea> pane = new VirtualizedScrollPane<>();

158-166: 初始化方法缺少对未成功初始化的处理

initialize方法调用了多个初始化辅助方法,但没有捕获或处理这些方法可能抛出的异常。如果初始化过程中出现问题,可能导致应用程序状态不一致。

添加异常处理:

@FXML
public void initialize() {
+    try {
        initializeOption();
        initializeUI();

        initializeUserDataBindings();
        initializeBindings();
        initializeUserData();
+    } catch (Exception e) {
+        StaticLog.error(e, "初始化HTTP工具失败");
+        notificationBuilder.text("初始化失败:" + e.getMessage());
+        notificationBuilder.showError();
+    }
}

70-74: 缺少导包

代码中使用了HttpResponseHttpHeaders类,但缺少相应的导入语句。虽然第69-70行有导入,但没有指定具体的包,建议使用明确的导入路径。

- import java.net.http.HttpHeaders;
- import java.net.http.HttpResponse;
+ import java.net.http.HttpHeaders;
+ import java.net.http.HttpResponse;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eceefde and 4a24945.

📒 Files selected for processing (6)
  • common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (1 hunks)
  • common/src/main/java/module-info.java (1 hunks)
  • common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml (1 hunks)
  • core/src/main/java/com/tlcsdm/core/javafx/richtext/InformationArea.java (1 hunks)
  • core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java (1 hunks)
  • core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • common/src/main/java/module-info.java
  • core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java
  • common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml
🧰 Additional context used
🪛 GitHub Check: CodeFactor
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java

[notice] 227-326: common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java#L227-L326
Complex Method

🪛 Biome (1.9.4)
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css

[error] 29-29: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 30-30: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 34-34: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 35-38: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 39-39: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build (21, macos-latest, false)
  • GitHub Check: build (21, windows-latest, false)
  • GitHub Check: build (17, windows-latest, false)
  • GitHub Check: build (21, ubuntu-latest, false)
  • GitHub Check: build (17, ubuntu-latest, false)
  • GitHub Check: build (17, macos-latest, false)
  • GitHub Check: qodana
  • GitHub Check: StepSecurity Harden-Runner
  • GitHub Check: Summary
🔇 Additional comments (3)
core/src/main/java/com/tlcsdm/core/javafx/richtext/InformationArea.java (1)

71-73: 添加了简便的文本设置方法

setText 方法增强了 InformationArea 组件的易用性,通过封装 replaceText 操作提供了更直观的接口。这与文档中提到的 JsonCodeArea 类的 setText 方法形成了一致的 API 设计。

core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (1)

28-44: JSON语法高亮样式规则

CSS样式规则定义合理,为JSON不同元素(键、值、括号等)提供了良好的视觉区分。建议考虑添加注释的英文翻译,以便非中文开发者理解。

另外,-fx-fill-fx-font-weight 属性是JavaFX特有的CSS扩展,某些CSS验证工具可能将其标记为错误,但在JavaFX环境中这些是有效的样式属性。

🧰 Tools
🪛 Biome (1.9.4)

[error] 29-29: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 30-30: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 34-34: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 35-38: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 39-39: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)

common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (1)

158-166:

❌ Incorrect review comment

未找到initializeUserDataBindingsinitializeBindingsinitializeUserData的实现

initialize方法调用了三个未在类中实现的方法:initializeUserDataBindingsinitializeBindingsinitializeUserData。这可能导致运行时错误。

如果这些方法应该被实现但尚未完成,请完成它们的实现;如果它们由父类提供,请确保它们能够适用于当前类。


🏁 Script executed:

#!/bin/bash
# 检查这些方法是否在父类中存在
grep -r "initializeUserDataBindings\|initializeBindings\|initializeUserData" --include="*.java" .

Length of output: 11136


🏁 Script executed:

#!/bin/bash
# 检查 HttpTool 类的声明和继承关系
sed -n '1,50p' common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java
rg "extends" -n common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java

Length of output: 2829


🏁 Script executed:

#!/bin/bash
# 查看 CommonSample 类及其方法定义
sed -n '1,200p' common/src/main/java/com/tlcsdm/jfxcommon/CommonSample.java

# 查找关键方法在 CommonSample 中的声明
rg -n "initializeBindings" common/src/main/java/com/tlcsdm/jfxcommon/CommonSample.java
rg -n "initializeUserDataBindings" common/src/main/java/com/tlcsdm/jfxcommon/CommonSample.java
rg -n "initializeUserData" common/src/main/java/com/tlcsdm/jfxcommon/CommonSample.java

Length of output: 2287


方法已在父类 SampleBase 中实现,无需在 HttpTool 中重复声明

initializeUserDataBindingsinitializeBindingsinitializeUserData 这三个方法均由 com.tlcsdm.frame.SampleBase 提供,HttpTool 通过继承 CommonSample(又继承自 SampleBase)可以直接使用父类实现,不会引发运行时错误。

请忽略先前关于“未找到这些方法实现”的评论。

Likely an incorrect or invalid review comment.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (6)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (6)

258-272: ⚠️ Potential issue

GET请求参数未经URL编码

当前代码直接将参数拼接到URL中,未进行URL编码,这可能导致请求失败或安全问题。

请对参数进行URL编码:

- paramsMap.forEach((key, value) -> paramsDataBuffer.append(key).append("=").append(value).append("&"));
+ paramsMap.forEach((key, value) -> {
+     try {
+         paramsDataBuffer.append(URLEncoder.encode(key, StandardCharsets.UTF_8))
+                 .append("=")
+                 .append(URLEncoder.encode(value, StandardCharsets.UTF_8))
+                 .append("&");
+     } catch (UnsupportedEncodingException e) {
+         throw new RuntimeException("编码不支持", e);
+     }
+ });

同时需要添加导入:

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

281-290: ⚠️ Potential issue

POST请求参数未经URL编码

POST请求的参数体构建没有进行URL编码,可能导致特殊字符处理错误。

请对表单参数进行URL编码:

- response = HttpUtil.doPost(url, headerMap, body);
+ response = HttpUtil.doPost(url, headerMap, encodeParameters(body));

并添加辅助方法:

private String encodeParameters(String input) {
    if (input == null || input.isEmpty()) {
        return input;
    }
    StringBuilder result = new StringBuilder();
    String[] params = input.split("&");
    for (String param : params) {
        int idx = param.indexOf("=");
        if (idx > 0) {
            String key = param.substring(0, idx);
            String value = param.substring(idx + 1);
            try {
                String encodedValue = URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
                result.append(key).append("=").append(encodedValue).append("&");
            } catch (Exception e) {
                // 异常情况下使用原始值
                result.append(param).append("&");
            }
        } else {
            result.append(param).append("&");
        }
    }
    // 移除末尾的'&'
    if (result.length() > 0) {
        result.setLength(result.length() - 1);
    }
    return result.toString();
}

302-306: 🛠️ Refactor suggestion

HTTP状态码处理过于严格

当前代码只将状态码200视为成功,忽略了其他有效的2xx状态码(如201、202、204等)。

修改状态码检查逻辑:

- if (response == null || response.statusCode() != 200) {
+ if (response == null) {
      notificationBuilder.text("请求失败");
      notificationBuilder.showError();
      return;
  }
+ if (response.statusCode() < 200 || response.statusCode() >= 300) {
+     notificationBuilder.text("请求失败,状态码:" + response.statusCode());
+     notificationBuilder.showWarning();
+     // 继续处理响应,显示错误信息
+ }

258-300: 🛠️ Refactor suggestion

在UI线程中执行网络请求

当前代码直接在JavaFX Application Thread中执行HTTP请求,这会导致UI冻结,影响用户体验。

建议在后台线程中执行HTTP请求:

CompletableFuture.supplyAsync(() -> {
    // 执行HTTP请求的代码
    HttpResponse<String> response = null;
    if ("GET".equals(methodString)) {
        // GET请求逻辑...
    } else if ("POST".equals(methodString)) {
        // POST请求逻辑...
    } // 其他请求类型...
    return response;
}).whenCompleteAsync((response, exception) -> {
    Platform.runLater(() -> {
        if (exception != null) {
            notificationBuilder.text("请求异常: " + exception.getMessage());
            notificationBuilder.showError();
        } else if (response == null) {
            notificationBuilder.text("请求失败");
            notificationBuilder.showError();
        } else {
            // 处理响应...
            renderResponse(response);
        }
    });
});

需要添加导入:

import java.util.concurrent.CompletableFuture;
import javafx.application.Platform;

314-316: ⚠️ Potential issue

响应头处理存在错误

代码错误地删除了响应头字符串缓冲区的第一个字符,这可能导致第一个响应头的首字符丢失。

移除不正确的字符删除逻辑:

- if (!headerStringBuffer.isEmpty()) {
-     headerStringBuffer.deleteCharAt(0);
- }

如果目的是移除末尾多余的换行符,应该修改为:

if (headerStringBuffer.length() > 0 && headerStringBuffer.charAt(headerStringBuffer.length() - 1) == '\n') {
    headerStringBuffer.deleteCharAt(headerStringBuffer.length() - 1);
}

132-133: ⚠️ Potential issue

国际化资源键不正确

当前使用的国际化资源键指向端口扫描工具(scanPortTool),而非HTTP工具。

请更新资源键为HTTP工具对应的键:

- return I18nUtils.get("common.tool.debug.scanPortTool.sampleDesc");
+ return I18nUtils.get("common.tool.debug.httpTool.sampleDesc");

同时确保在国际化资源文件中添加了对应的键值对。

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4a24945 and d04d2d9.

📒 Files selected for processing (2)
  • common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (1 hunks)
  • core/src/main/java/com/tlcsdm/core/util/DependencyUtil.java (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
core/src/main/java/com/tlcsdm/core/util/DependencyUtil.java (1)
core/src/main/java/com/tlcsdm/core/util/CoreUtil.java (1)
  • CoreUtil (58-303)
🪛 GitHub Check: CodeFactor
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java

[notice] 226-325: common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java#L226-L325
Complex Method

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: qodana
  • GitHub Check: build (17, windows-latest, false)
  • GitHub Check: build (21, windows-latest, false)
  • GitHub Check: build (21, macos-latest, false)
  • GitHub Check: build (21, ubuntu-latest, false)
  • GitHub Check: build (17, ubuntu-latest, false)
  • GitHub Check: build (17, macos-latest, false)
  • GitHub Check: StepSecurity Harden-Runner
  • GitHub Check: Summary
🔇 Additional comments (20)
core/src/main/java/com/tlcsdm/core/util/DependencyUtil.java (13)

41-46: 修复了中文注释中的错字

你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。


48-53: 修复了中文注释中的错字

你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。


55-60: 修复了中文注释中的错字

你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。


62-67: 修复了中文注释中的错字

你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。


69-74: 修复了中文注释中的错字

你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。


76-81: 修复了中文注释中的错字

你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。


83-88: 修复了中文注释中的错字

你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。


90-95: 修复了中文注释中的错字

你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。


97-102: 修复了中文注释中的错字

你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。


104-109: 修复了中文注释中的错字

你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。


111-116: 修复了中文注释中的错字

你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。


118-123: 修复了中文注释中的错字

你修正了方法注释中的"因否存在"为"是否存在",这提高了代码的可读性和专业性。


125-130: 添加了对RichTextFX依赖的检测方法

该方法检测是否存在RichTextFX库,通过验证org.fxmisc.richtext.CodeArea类的存在性,这与PR中引入的HttpTool功能相关联。实现简洁且与类中的其他方法保持一致。

common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (7)

1-80: HTTP调试工具类的实现

代码实现了一个基于JavaFX的HTTP调试工具,包括了必要的导入和类定义。类继承自CommonSample,并添加了必要的注释和版权信息。


82-114: UI组件定义

定义了各种UI组件用于HTTP请求的构建和显示,包括URL输入、方法选择、参数/头部/Cookie表格等。组织结构清晰,变量命名合理。


158-161: 根据RichTextFX依赖判断工具可见性

通过DependencyUtil.hasRichTextFX()判断工具的可见性,这是一个很好的做法,确保只在必要的依赖存在时才显示此工具。这与新增的hasRichTextFX()方法相匹配。


173-188: UI初始化方法实现

初始化选项和表格列的实现良好,代码结构清晰,复用了设置表格列映射的逻辑。


190-224: UI事件和上下文菜单设置

添加了参数输入方式切换的监听器,设置了表格右键菜单,以及JSON格式化和压缩功能。很好地利用了依赖检测来有条件地添加JSON处理功能。


326-348: UI操作方法实现

添加参数行和浏览器打开功能的方法实现简洁明了,逻辑正确。


350-379: 表格辅助方法实现

表格列设置和右键菜单事件处理的实现良好,代码结构清晰,功能完整。

Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (5)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (5)

132-135: 资源键引用错误

此方法使用了与ScanPortTool工具相关的国际化资源键,而不是适用于HttpTool的正确键:

- return I18nUtils.get("common.tool.debug.scanPortTool.sampleDesc");
+ return I18nUtils.get("common.tool.debug.httpTool.sampleDesc");

请确保在国际化资源文件中添加与HttpTool相对应的描述文本。


228-330: sendAction方法过于复杂,需要重构

该方法承担了多项职责(输入验证、参数构建、请求发送、响应处理等),总计超过100行代码,难以维护和测试。应将其拆分为多个职责单一的小方法:

  1. validateInput() - 验证URL输入
  2. buildRequestParams() - 构建请求参数和头信息
  3. executeRequest() - 执行HTTP请求
  4. processResponse() - 处理响应结果并更新UI

这种改进将使代码更易于维护、测试和理解。

🧰 Tools
🪛 GitHub Check: CodeFactor

[notice] 228-331: common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java#L228-L331
Complex Method


280-295: 非GET请求参数未进行URL编码

构建非GET请求体时没有对参数值进行URL编码,这可能导致特殊字符问题。请对参数值进行编码:

 StringBuilder sb = new StringBuilder();
 for (Map<String, String> map : paramsDatatableData) {
-    sb.append(map.get("name"));
-    sb.append("=");
-    sb.append(map.get("value"));
+    sb.append(URLEncoder.encode(map.get("name"), StandardCharsets.UTF_8));
+    sb.append("=");
+    sb.append(URLEncoder.encode(map.get("value"), StandardCharsets.UTF_8));
     sb.append("&");
 }
 String body = sb.toString();

同样,POST请求时应对参数进行编码:

- response = HttpUtil.doPost(url, headerMap, body);
+ response = HttpUtil.doPost(url, headerMap, encodeParameters(body));

并添加一个编码辅助方法:

private String encodeParameters(String input) {
    if (input == null || input.isEmpty()) {
        return input;
    }
    
    // 如参数已URL编码,则直接返回
    if (input.contains("%")) {
        return input;
    }
    
    StringBuilder result = new StringBuilder();
    for (String param : input.split("&")) {
        if (param.isEmpty()) continue;
        
        int idx = param.indexOf("=");
        if (idx > 0) {
            String key = param.substring(0, idx);
            String value = param.substring(idx + 1);
            result.append(key).append("=")
                  .append(URLEncoder.encode(value, StandardCharsets.UTF_8))
                  .append("&");
        } else {
            result.append(param).append("&");
        }
    }
    if (result.length() > 0) {
        result.setLength(result.length() - 1);
    }
    return result.toString();
}

308-312: HTTP状态码处理过于严格

当前代码仅将状态码200视为成功,忽略了其他有效的2xx状态码(如201、202、204等)。即使状态码不是2xx,响应头和体仍可能包含有用信息:

- if (response == null || response.statusCode() != 200) {
+ if (response == null) {
      notificationBuilder.text("请求失败");
      notificationBuilder.showError();
      return;
  }
+ // 处理非2xx状态码,但仍显示响应信息
+ if (response.statusCode() < 200 || response.statusCode() >= 300) {
+     notificationBuilder.text("请求返回状态码:" + response.statusCode());
+     notificationBuilder.showWarning();
+     // 继续处理响应,不要直接返回
+ }

这样做可以在非成功状态下仍然显示服务器返回的错误信息,对调试更友好。


320-322: 响应头处理逻辑错误

当前代码错误地删除了响应头字符串的第一个字符,这会导致第一个响应头名称的首字符被删除:

- if (!headerStringBuffer.isEmpty()) {
-     headerStringBuffer.deleteCharAt(0);
- }

此代码可能是误将删除最后一个字符(如分隔符)的逻辑写成了删除第一个字符。如果目的是移除最后的换行符,应改为:

if (headerStringBuffer.length() > 0 && headerStringBuffer.charAt(headerStringBuffer.length() - 1) == '\n') {
    headerStringBuffer.deleteCharAt(headerStringBuffer.length() - 1);
}

或者,如果不需要删除任何字符,可以直接删除这段代码。

🧹 Nitpick comments (3)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (3)

260-305: 使用策略模式或枚举映射替代冗长的条件判断

当前使用了大量if-else语句处理不同HTTP方法,可以改用更优雅的解决方案:

- if ("GET".equals(methodString)) {
-    // GET实现
- } else {
-    // 其他方法实现
-    if ("POST".equals(methodString)) {
-        // POST实现
-    } else if ("HEAD".equals(methodString)) {
-        // HEAD实现
-    } else if ("PUT".equals(methodString)) {
-        // PUT实现
-    } // 更多条件...
- }
+ // 策略模式或者枚举映射实现
+ Map<String, HttpRequestHandler> requestHandlers = Map.of(
+     "GET", this::handleGetRequest,
+     "POST", this::handlePostRequest,
+     "HEAD", this::handleHeadRequest,
+     "PUT", this::handlePutRequest,
+     "PATCH", this::handlePatchRequest,
+     "DELETE", this::handleDeleteRequest
+ );
+ 
+ HttpResponse<String> response = requestHandlers.getOrDefault(methodString, this::handleDefaultRequest).execute(url, headerMap, paramsMap);

这样可以避免复杂的条件判断,使代码更易于扩展和维护。


192-204: 使用JavaFX绑定简化UI状态控制

当前使用了监听器来控制参数UI的可见性,可以使用JavaFX的绑定功能使代码更简洁:

- paramsDataIsStringCheckBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
-     @Override
-     public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
-         if (newValue) {
-             paramsDataTextArea.setVisible(true);
-             paramsDataTableView.setVisible(false);
-         } else {
-             paramsDataTextArea.setVisible(false);
-             paramsDataTableView.setVisible(true);
-         }
-     }
- });
+ // 使用绑定表达式直接控制UI元素可见性
+ paramsDataTextArea.visibleProperty().bind(paramsDataIsStringCheckBox.selectedProperty());
+ paramsDataTableView.visibleProperty().bind(paramsDataIsStringCheckBox.selectedProperty().not());

这样写更符合JavaFX的声明式风格,代码更简洁且易于维护。


366-385: TableView右键菜单应在初始化时创建,而非每次点击时创建

当前代码在每次右键点击时都创建新的ContextMenu,这不仅效率低,还可能导致内存泄漏:

- paramsDataTableView.setOnMouseClicked(event -> {
-     if (event.getButton() == MouseButton.SECONDARY && !paramsDatatableData.isEmpty()) {
-         MenuItem menu_Copy = new MenuItem("复制选中行");
-         menu_Copy.setOnAction(event1 -> {
-             Map<String, String> tableBean = paramsDataTableView.getSelectionModel().getSelectedItem();
-             Map<String, String> tableBean2 = new HashMap<>(tableBean);
-             paramsDatatableData.add(paramsDataTableView.getSelectionModel().getSelectedIndex(), tableBean2);
-         });
-         MenuItem menu_Remove = new MenuItem("删除选中行");
-         menu_Remove.setOnAction(event1 -> {
-             paramsDatatableData.remove(paramsDataTableView.getSelectionModel().getSelectedIndex());
-         });
-         MenuItem menu_RemoveAll = new MenuItem("删除所有");
-         menu_RemoveAll.setOnAction(event1 -> {
-             paramsDatatableData.clear();
-         });
-         paramsDataTableView.setContextMenu(new ContextMenu(menu_Copy, menu_Remove, menu_RemoveAll));
-     }
- });
+ // 创建上下文菜单及菜单项
+ MenuItem menu_Copy = new MenuItem("复制选中行");
+ menu_Copy.setOnAction(event1 -> {
+     if (paramsDataTableView.getSelectionModel().getSelectedItem() != null) {
+         Map<String, String> tableBean = paramsDataTableView.getSelectionModel().getSelectedItem();
+         Map<String, String> tableBean2 = new HashMap<>(tableBean);
+         paramsDatatableData.add(paramsDataTableView.getSelectionModel().getSelectedIndex(), tableBean2);
+     }
+ });
+ 
+ MenuItem menu_Remove = new MenuItem("删除选中行");
+ menu_Remove.setOnAction(event1 -> {
+     if (paramsDataTableView.getSelectionModel().getSelectedIndex() >= 0) {
+         paramsDatatableData.remove(paramsDataTableView.getSelectionModel().getSelectedIndex());
+     }
+ });
+ 
+ MenuItem menu_RemoveAll = new MenuItem("删除所有");
+ menu_RemoveAll.setOnAction(event1 -> {
+     paramsDatatableData.clear();
+ });
+ 
+ ContextMenu contextMenu = new ContextMenu(menu_Copy, menu_Remove, menu_RemoveAll);
+ 
+ // 根据数据集状态动态控制菜单可用性
+ paramsDataTableView.setOnContextMenuRequested(event -> {
+     boolean hasItems = !paramsDatatableData.isEmpty();
+     boolean hasSelection = paramsDataTableView.getSelectionModel().getSelectedItem() != null;
+     
+     menu_Copy.setDisable(!hasSelection);
+     menu_Remove.setDisable(!hasSelection);
+     menu_RemoveAll.setDisable(!hasItems);
+     
+     if (hasItems) {
+         contextMenu.show(paramsDataTableView, event.getScreenX(), event.getScreenY());
+     }
+ });
+ 
+ paramsDataTableView.setContextMenu(contextMenu);

这种方式更高效、更符合JavaFX的设计模式,并能更好地处理菜单项的启用/禁用状态。

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d04d2d9 and 1da8494.

📒 Files selected for processing (3)
  • common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (1 hunks)
  • core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java (1 hunks)
  • core/src/main/java/com/tlcsdm/core/util/JacksonUtil.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • core/src/main/java/com/tlcsdm/core/util/JacksonUtil.java
  • core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java
🧰 Additional context used
🪛 GitHub Check: CodeFactor
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java

[notice] 228-331: common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java#L228-L331
Complex Method

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build (21, windows-latest, false)
  • GitHub Check: build (21, macos-latest, false)
  • GitHub Check: build (17, macos-latest, false)
  • GitHub Check: build (21, ubuntu-latest, false)
  • GitHub Check: build (17, windows-latest, false)
  • GitHub Check: build (17, ubuntu-latest, false)
  • GitHub Check: qodana
  • GitHub Check: StepSecurity Harden-Runner
  • GitHub Check: Summary

Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (3)

51-52: 改进GET请求方法返回类型并添加超时设置

将doGet方法返回类型从String改为HttpResponse,提供更完整的响应信息(包括状态码、头信息等),并统一添加了10秒超时设置。

考虑将超时时间作为可配置参数,以便应对不同网络环境或大型数据传输场景:

-public static HttpResponse<String> doGet(String url, Map<String, String> header) {
-    var builder = HttpRequest.newBuilder().uri(URI.create(url)).timeout(Duration.ofSeconds(10)).GET();
+public static HttpResponse<String> doGet(String url, Map<String, String> header) {
+    return doGet(url, header, 10);
+}
+
+public static HttpResponse<String> doGet(String url, Map<String, String> header, int timeoutSeconds) {
+    var builder = HttpRequest.newBuilder().uri(URI.create(url)).timeout(Duration.ofSeconds(timeoutSeconds)).GET();

137-147: 优化:基于操作系统动态设置User-Agent

根据不同操作系统(Windows、Mac、Linux)设置对应的User-Agent,使HTTP请求更符合真实环境。

建议对所有操作系统情况进行明确处理,包括WINDOWS和UNKNOWN情况:

String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.50";
switch (OSUtil.getOS()) {
+   case WINDOWS:
+       userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.50";
+       break;
    case MAC:
        userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36";
        break;
    case LINUX:
        userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36";
        break;
+   case UNKNOWN:
+       // 使用默认Windows User-Agent或创建通用User-Agent
+       break;
}

149-154: 改进execute方法返回完整的HTTP响应

将execute方法更新为直接返回HttpResponse对象,而不是之前只返回响应体内容,提供了更完整的HTTP响应信息。

当发生异常时,方法返回null但没有相关文档说明,这可能导致调用方出现NullPointerException。建议添加注释说明可能返回null的情况,或者考虑使用Optional包装返回值:

-private static HttpResponse<String> execute(HttpRequest.Builder builder, Charset charset) {
+/**
+ * 执行HTTP请求并返回响应
+ * 
+ * @param builder 请求构建器
+ * @param charset 字符集
+ * @return HTTP响应对象,如果发生异常则返回null
+ */
+private static HttpResponse<String> execute(HttpRequest.Builder builder, Charset charset) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1da8494 and 247eb45.

📒 Files selected for processing (1)
  • core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (1)
core/src/main/java/com/tlcsdm/core/javafx/util/OSUtil.java (1)
  • OSUtil (46-185)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build (21, windows-latest, false)
  • GitHub Check: build (17, windows-latest, false)
  • GitHub Check: build (21, ubuntu-latest, false)
  • GitHub Check: build (21, macos-latest, false)
  • GitHub Check: build (17, ubuntu-latest, false)
  • GitHub Check: build (17, macos-latest, false)
  • GitHub Check: qodana
  • GitHub Check: StepSecurity Harden-Runner
  • GitHub Check: Summary
🔇 Additional comments (8)
core/src/main/java/com/tlcsdm/core/util/HttpUtil.java (8)

32-32: 添加OSUtil导入以支持多平台User-Agent设置

为了支持根据不同操作系统设置对应的User-Agent,这里添加了OSUtil类的导入。


40-40: 导入Duration类以支持超时设置

添加java.time.Duration导入用于为HTTP请求设置超时时间,这是一个很好的改进。


60-65: 改进POST请求方法返回类型并添加超时设置

将doPost方法返回类型从String改为HttpResponse,并统一添加了10秒超时设置,使API更一致且信息更完整。


67-75: 添加PUT请求支持

新增doPut方法实现PUT请求支持,遵循了与其他HTTP方法一致的编码风格和接口设计,包括10秒超时设置。


77-84: 添加DELETE请求支持

新增doDelete方法实现DELETE请求支持,结构清晰简洁,与GET方法类似(无需请求体)。


86-95: 添加PATCH请求支持

新增doPatch方法实现PATCH请求支持,使用method()方法显式指定HTTP方法类型,实现逻辑完整。


97-105: 添加HEAD请求支持

新增doHead方法实现HEAD请求支持,使用noBody()表示无请求体,符合HEAD请求的规范。


110-110: 更新表单POST请求返回类型

将doPostForm方法返回类型从String改为HttpResponse,保持与其他HTTP方法的一致性。

Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (1)

45-45: 建议添加文件末尾换行符
为符合 POSIX 标准并避免某些工具在处理时出现警告,建议在文件末尾补充一个换行符。

🧰 Tools
🪛 Biome (1.9.4)

[error] 45-45: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 247eb45 and 94efefe.

📒 Files selected for processing (2)
  • core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java (1 hunks)
  • core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • core/src/main/java/com/tlcsdm/core/javafx/richtext/JsonCodeArea.java
🧰 Additional context used
🪛 Biome (1.9.4)
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css

[error] 29-29: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 30-30: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 34-34: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 35-38: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 39-39: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: qodana
  • GitHub Check: build (21, macos-latest, false)
  • GitHub Check: build (17, windows-latest, false)
  • GitHub Check: build (17, macos-latest, false)
  • GitHub Check: build (17, ubuntu-latest, false)
  • GitHub Check: build (21, windows-latest, false)
  • GitHub Check: build (21, ubuntu-latest, false)
  • GitHub Check: StepSecurity Harden-Runner
  • GitHub Check: Summary
🔇 Additional comments (5)
core/src/main/resources/com/tlcsdm/core/static/javafx/richtext/json-keywords.css (5)

1-26: 许可声明完整且符合要求
许可证头部详细说明了使用条款和免责声明,符合开源规范,无需修改。


28-31: JSON 键的样式定义正确
.text-json-area .key 使用了 JavaFX CSS 有效属性 -fx-fill-fx-font-weight,实现了预期的高亮和加粗效果。

🧰 Tools
🪛 Biome (1.9.4)

[error] 29-29: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


[error] 30-30: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


33-36: JSON 值的样式定义正确
.text-json-area .value 同样采用了 JavaFX CSS 属性,无语法或逻辑问题。

🧰 Tools
🪛 Biome (1.9.4)

[error] 34-34: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


38-40: 大括号和中括号样式定义正确
.brace.bracket 选择器配色清晰,符合 JSON 语法高亮需求。

🧰 Tools
🪛 Biome (1.9.4)

[error] 39-39: Unknown property is not allowed.

See CSS Specifications and browser specific properties for more details.
To resolve this issue, replace the unknown property with a valid CSS property.

(lint/correctness/noUnknownProperty)


42-44: 逗号与冒号样式定义正确
使用黑色填充,视觉上与其他元素区分度高,满足可读性需求。

Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (6)
common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (6)

275-292: POST请求参数未正确编码

当构建POST请求体时,参数值未经过URL编码,这可能导致特殊字符处理错误。


316-318: 响应头处理错误

代码错误地删除了响应头字符串的第一个字符,这会导致第一个响应头的第一个字符丢失。


225-326: sendAction方法过于复杂

此方法职责过多,包括输入验证、请求构建、执行请求和处理响应,代码行数过多(超过90行),难以维护和测试。


344-350: 🛠️ Refactor suggestion

缺少URL验证

在打开浏览器前,代码仅检查URL是否为空,但未验证格式是否正确。

建议添加URL验证:

@FXML
private void toBrowerAction(ActionEvent event) {
    String url = urlTextField.getText();
-    if (url.isEmpty()) {
+    if (url.isEmpty() || !isValidUrl(url)) {
+        notificationBuilder.text(I18nUtils.get("common.tool.debug.httpTool.error.invalidUrl"));
+        notificationBuilder.showWarning();
        return;
    }
    CoreUtil.openWeb(url);
}

+/**
+ * 验证URL是否有效
+ */
+private boolean isValidUrl(String url) {
+    try {
+        new java.net.URL(url).toURI();
+        return true;
+    } catch (Exception e) {
+        return false;
+    }
+}

304-308: 🛠️ Refactor suggestion

HTTP状态码处理过于严格

代码仅将状态码200视为成功,忽略了其他有效的成功状态码(如201、202、204等)。

建议修改为:

- if (response == null || response.statusCode() != 200) {
+ if (response == null) {
      notificationBuilder.text(I18nUtils.get("common.tool.debug.httpTool.error.request"));
      notificationBuilder.showError();
      return;
+ }
+ // 2xx状态码都表示成功
+ if (response.statusCode() < 200 || response.statusCode() >= 300) {
+     notificationBuilder.text(I18nUtils.get("common.tool.debug.httpTool.error.request") + " - " + response.statusCode());
+     notificationBuilder.showWarning();
+     // 继续处理响应,以便用户可以查看错误详情
  }

322-325: 🛠️ Refactor suggestion

缺少响应类型检查

代码尝试将所有响应格式化为JSON,而没有检查Content-Type是否真的是JSON。

建议修改为:

HttpHeaders headers = response.headers();
+
+// 获取Content-Type并根据类型处理响应
+String contentType = headers.firstValue("Content-Type").orElse("");
+boolean isJsonResponse = contentType.contains("application/json") || 
+                         contentType.contains("text/json") ||
+                         (response.body().startsWith("{") && response.body().endsWith("}")) ||
+                         (response.body().startsWith("[") && response.body().endsWith("]"));

StringBuffer headerStringBuffer = new StringBuffer();
headers.map().forEach((name, values) -> {
    String value = String.join(", ", values);
    headerStringBuffer.append(name).append(":").append(value).append("\n");
});

ResponseHeaderTextArea.setText(headerStringBuffer.toString());
String res = response.body();
-if (DependencyUtil.hasJackson()) {
+if (DependencyUtil.hasJackson() && isJsonResponse) {
    res = JacksonUtil.formatJson(res);
}
ResponseBodyTextArea.setText(res);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 94efefe and 4837b8e.

📒 Files selected for processing (5)
  • common/src/main/java/com/tlcsdm/jfxcommon/debug/HttpTool.java (1 hunks)
  • common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml (1 hunks)
  • common/src/main/resources/com/tlcsdm/jfxcommon/i18n/messages_en.properties (1 hunks)
  • common/src/main/resources/com/tlcsdm/jfxcommon/i18n/messages_ja.properties (1 hunks)
  • common/src/main/resources/com/tlcsdm/jfxcommon/i18n/messages_zh.properties (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • common/src/main/resources/com/tlcsdm/jfxcommon/i18n/messages_zh.properties
  • common/src/main/resources/com/tlcsdm/jfxcommon/i18n/messages_en.properties
  • common/src/main/resources/com/tlcsdm/jfxcommon/i18n/messages_ja.properties
🚧 Files skipped from review as they are similar to previous changes (1)
  • common/src/main/resources/com/tlcsdm/jfxcommon/fxml/httpTool.fxml
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: qodana
  • GitHub Check: build (21, windows-latest, false)
  • GitHub Check: build (21, ubuntu-latest, false)
  • GitHub Check: build (21, macos-latest, false)
  • GitHub Check: build (17, windows-latest, false)
  • GitHub Check: build (17, ubuntu-latest, false)
  • GitHub Check: build (17, macos-latest, false)
  • GitHub Check: StepSecurity Harden-Runner
  • GitHub Check: Summary

Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
Signed-off-by: unknowIfGuestInDream <liang.tang.cx@gmail.com>
Copy link

@unknowIfGuestInDream unknowIfGuestInDream merged commit 58342e1 into master May 11, 2025
31 checks passed
@unknowIfGuestInDream unknowIfGuestInDream deleted the gh-1007 branch May 11, 2025 03:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature Request] Http接口测试i工具
1 participant