Compare commits
22
Commits
v0.0.12
...
a3de2cc246
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a3de2cc246 | ||
|
|
c7dc033bad | ||
|
|
a1726bf3b2 | ||
|
|
35c63c4b83 | ||
|
|
25c3944d5f | ||
|
|
ba9fa7ef97 | ||
|
|
c9c7c098c8 | ||
|
|
a4a9317731 | ||
|
|
cf701b18fa | ||
|
|
f42b833e3e | ||
|
|
ebaeb1ac56 | ||
|
|
7e1ff1343d | ||
|
|
45124eba81 | ||
|
|
8736aa44c4 | ||
|
|
4cd0b2338d | ||
|
|
c2cb8771ce | ||
|
|
35fa531be9 | ||
|
|
2bec0773ac | ||
|
|
b690656848 | ||
|
|
189005098b | ||
|
|
99cbf30d12 | ||
|
|
3a46327129 |
@@ -0,0 +1,2 @@
|
||||
/cache
|
||||
/project.local.yml
|
||||
@@ -0,0 +1,154 @@
|
||||
# the name by which the project can be referenced within Serena
|
||||
project_name: "timi-spring"
|
||||
|
||||
|
||||
# list of languages for which language servers are started; choose from:
|
||||
# al bash clojure cpp csharp
|
||||
# csharp_omnisharp dart elixir elm erlang
|
||||
# fortran fsharp go groovy haskell
|
||||
# haxe java julia kotlin lua
|
||||
# markdown
|
||||
# matlab nix pascal perl php
|
||||
# php_phpactor powershell python python_jedi r
|
||||
# rego ruby ruby_solargraph rust scala
|
||||
# swift terraform toml typescript typescript_vts
|
||||
# vue yaml zig
|
||||
# (This list may be outdated. For the current list, see values of Language enum here:
|
||||
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py
|
||||
# For some languages, there are alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
|
||||
# Note:
|
||||
# - For C, use cpp
|
||||
# - For JavaScript, use typescript
|
||||
# - For Free Pascal/Lazarus, use pascal
|
||||
# Special requirements:
|
||||
# Some languages require additional setup/installations.
|
||||
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
|
||||
# When using multiple languages, the first language server that supports a given file will be used for that file.
|
||||
# The first language is the default language and the respective language server will be used as a fallback.
|
||||
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
|
||||
languages:
|
||||
- java
|
||||
|
||||
# the encoding used by text files in the project
|
||||
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
|
||||
encoding: "utf-8"
|
||||
|
||||
# line ending convention to use when writing source files.
|
||||
# Possible values: unset (use global setting), "lf", "crlf", or "native" (platform default)
|
||||
# This does not affect Serena's own files (e.g. memories and configuration files), which always use native line endings.
|
||||
line_ending:
|
||||
|
||||
# The language backend to use for this project.
|
||||
# If not set, the global setting from serena_config.yml is used.
|
||||
# Valid values: LSP, JetBrains
|
||||
# Note: the backend is fixed at startup. If a project with a different backend
|
||||
# is activated post-init, an error will be returned.
|
||||
language_backend:
|
||||
|
||||
# whether to use project's .gitignore files to ignore files
|
||||
ignore_all_files_in_gitignore: true
|
||||
|
||||
# advanced configuration option allowing to configure language server-specific options.
|
||||
# Maps the language key to the options.
|
||||
# Have a look at the docstring of the constructors of the LS implementations within solidlsp (e.g., for C# or PHP) to see which options are available.
|
||||
# No documentation on options means no options are available.
|
||||
ls_specific_settings: {}
|
||||
|
||||
# list of additional paths to ignore in this project.
|
||||
# Same syntax as gitignore, so you can use * and **.
|
||||
# Note: global ignored_paths from serena_config.yml are also applied additively.
|
||||
ignored_paths: []
|
||||
|
||||
# whether the project is in read-only mode
|
||||
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
|
||||
# Added on 2025-04-18
|
||||
read_only: false
|
||||
|
||||
# list of tool names to exclude.
|
||||
# This extends the existing exclusions (e.g. from the global configuration)
|
||||
#
|
||||
# Below is the complete list of tools for convenience.
|
||||
# To make sure you have the latest list of tools, and to view their descriptions,
|
||||
# execute `uv run scripts/print_tool_overview.py`.
|
||||
#
|
||||
# * `activate_project`: Activates a project based on the project name or path.
|
||||
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
|
||||
# * `create_text_file`: Creates/overwrites a file in the project directory.
|
||||
# * `delete_memory`: Delete a memory file. Should only happen if a user asks for it explicitly,
|
||||
# for example by saying that the information retrieved from a memory file is no longer correct
|
||||
# or no longer relevant for the project.
|
||||
# * `edit_memory`: Replaces content matching a regular expression in a memory.
|
||||
# * `execute_shell_command`: Executes a shell command.
|
||||
# * `find_file`: Finds files in the given relative paths
|
||||
# * `find_referencing_symbols`: Finds symbols that reference the given symbol using the language server backend
|
||||
# * `find_symbol`: Performs a global (or local) search using the language server backend.
|
||||
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
||||
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
|
||||
# * `initial_instructions`: Provides instructions Serena usage (i.e. the 'Serena Instructions Manual')
|
||||
# for clients that do not read the initial instructions when the MCP server is connected.
|
||||
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
|
||||
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
|
||||
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
|
||||
# * `list_memories`: List available memories. Any memory can be read using the `read_memory` tool.
|
||||
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
||||
# * `read_file`: Reads a file within the project directory.
|
||||
# * `read_memory`: Read the content of a memory file. This tool should only be used if the information
|
||||
# is relevant to the current task. You can infer whether the information
|
||||
# is relevant from the memory file name.
|
||||
# You should not read the same memory file multiple times in the same conversation.
|
||||
# * `rename_memory`: Renames or moves a memory. Moving between project and global scope is supported
|
||||
# (e.g., renaming "global/foo" to "bar" moves it from global to project scope).
|
||||
# * `rename_symbol`: Renames a symbol throughout the codebase using language server refactoring capabilities.
|
||||
# For JB, we use a separate tool.
|
||||
# * `replace_content`: Replaces content in a file (optionally using regular expressions).
|
||||
# * `replace_symbol_body`: Replaces the full definition of a symbol using the language server backend.
|
||||
# * `safe_delete_symbol`:
|
||||
# * `search_for_pattern`: Performs a search for a pattern in the project.
|
||||
# * `write_memory`: Write some information (utf-8-encoded) about this project that can be useful for future tasks to a memory in md format.
|
||||
# The memory name should be meaningful.
|
||||
excluded_tools: []
|
||||
|
||||
# list of tools to include that would otherwise be disabled (particularly optional tools that are disabled by default).
|
||||
# This extends the existing inclusions (e.g. from the global configuration).
|
||||
included_optional_tools: []
|
||||
|
||||
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
|
||||
# This cannot be combined with non-empty excluded_tools or included_optional_tools.
|
||||
fixed_tools: []
|
||||
|
||||
# list of mode names to that are always to be included in the set of active modes
|
||||
# The full set of modes to be activated is base_modes + default_modes.
|
||||
# If the setting is undefined, the base_modes from the global configuration (serena_config.yml) apply.
|
||||
# Otherwise, this setting overrides the global configuration.
|
||||
# Set this to [] to disable base modes for this project.
|
||||
# Set this to a list of mode names to always include the respective modes for this project.
|
||||
base_modes:
|
||||
|
||||
# list of mode names that are to be activated by default.
|
||||
# The full set of modes to be activated is base_modes + default_modes.
|
||||
# If the setting is undefined, the default_modes from the global configuration (serena_config.yml) apply.
|
||||
# Otherwise, this overrides the setting from the global configuration (serena_config.yml).
|
||||
# This setting can, in turn, be overridden by CLI parameters (--mode).
|
||||
default_modes:
|
||||
|
||||
# initial prompt for the project. It will always be given to the LLM upon activating the project
|
||||
# (contrary to the memories, which are loaded on demand).
|
||||
initial_prompt: ""
|
||||
|
||||
# time budget (seconds) per tool call for the retrieval of additional symbol information
|
||||
# such as docstrings or parameter information.
|
||||
# This overrides the corresponding setting in the global configuration; see the documentation there.
|
||||
# If null or missing, use the setting from the global configuration.
|
||||
symbol_info_budget:
|
||||
|
||||
# list of regex patterns which, when matched, mark a memory entry as read‑only.
|
||||
# Extends the list from the global configuration, merging the two lists.
|
||||
read_only_memory_patterns: []
|
||||
|
||||
# list of regex patterns for memories to completely ignore.
|
||||
# Matching memories will not appear in list_memories or activate_project output
|
||||
# and cannot be accessed via read_memory or write_memory.
|
||||
# To access ignored memory files, use the read_file tool on the raw file path.
|
||||
# Extends the list from the global configuration, merging the two lists.
|
||||
# Example: ["_archive/.*", "_episodes/.*"]
|
||||
ignored_memory_patterns: []
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
<groupId>com.imyeyu.spring</groupId>
|
||||
<artifactId>timi-spring</artifactId>
|
||||
<version>0.0.12</version>
|
||||
<version>0.1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<properties>
|
||||
@@ -139,9 +139,9 @@
|
||||
<version>2.13.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.imyeyu.io</groupId>
|
||||
<artifactId>timi-io</artifactId>
|
||||
<version>0.0.3</version>
|
||||
<groupId>com.imyeyu.lang</groupId>
|
||||
<artifactId>timi-lang</artifactId>
|
||||
<version>0.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
|
||||
@@ -2,10 +2,10 @@ package com.imyeyu.spring;
|
||||
|
||||
import com.imyeyu.io.IO;
|
||||
import com.imyeyu.java.TimiJava;
|
||||
import com.imyeyu.java.bean.Language;
|
||||
import com.imyeyu.java.bean.timi.TimiCode;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.java.bean.ActionException;
|
||||
import com.imyeyu.java.bean.ResultCode;
|
||||
import com.imyeyu.java.ref.Ref;
|
||||
import com.imyeyu.lang.bean.Language;
|
||||
import com.imyeyu.spring.bean.RequestRange;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
@@ -45,13 +45,13 @@ public class TimiSpring {
|
||||
* 获取 Servlet 请求属性
|
||||
*
|
||||
* @return Servlet 请求属性
|
||||
* @throws TimiException 请求异常
|
||||
* @throws ActionException 请求异常
|
||||
*/
|
||||
public static ServletRequestAttributes getServletRequestAttributes() {
|
||||
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes sra) {
|
||||
return sra;
|
||||
}
|
||||
throw new TimiException(TimiCode.ERROR_NPE_VARIABLE);
|
||||
throw new ActionException(ResultCode.ERROR_NPE_VARIABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,7 +109,7 @@ public class TimiSpring {
|
||||
*/
|
||||
public static String cutURIStartAt(String flag) {
|
||||
int indexOf = getURI().indexOf(flag);
|
||||
TimiException.requiredTrue(-1 < indexOf, "not found flag: %s".formatted(flag));
|
||||
ActionException.requiredTrue(-1 < indexOf, "not found flag: %s".formatted(flag));
|
||||
return getURI().substring(indexOf + flag.length());
|
||||
}
|
||||
|
||||
@@ -346,7 +346,16 @@ public class TimiSpring {
|
||||
* @return 令牌
|
||||
*/
|
||||
public static String getToken() {
|
||||
return TimiJava.firstNotEmpty(getHeader("Token"), getHeader("token"), getRequestArg("token"), getRequestArg("Token"));
|
||||
return TimiJava.firstNotEmpty(getHeader("Token"), getHeader("token"), getRequestArg("Token"), getRequestArg("token"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取请求密钥,键为 Key 或 key,包括请求头和 URI
|
||||
*
|
||||
* @return 密钥
|
||||
*/
|
||||
public static String getKey() {
|
||||
return TimiJava.firstNotEmpty(getHeader("Key"), getHeader("key"), getRequestArg("Key"), getRequestArg("key"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -390,7 +399,7 @@ public class TimiSpring {
|
||||
* 获取请求 IP
|
||||
*
|
||||
* @return 请求 IP
|
||||
* @throws TimiException 服务异常
|
||||
* @throws ActionException 服务异常
|
||||
*/
|
||||
public static String getRequestIP() {
|
||||
String ip = getHeader("x-forwarded-for");
|
||||
@@ -427,17 +436,57 @@ public class TimiSpring {
|
||||
*/
|
||||
public static RequestRange getRequestRange(long total) throws IOException {
|
||||
HttpServletResponse resp = getResponse();
|
||||
|
||||
String range = getRequestAttrAsString("Range");
|
||||
if (range == null || !range.startsWith("bytes=")) {
|
||||
String range = getHeader("Range");
|
||||
if (TimiJava.isEmpty(range)) {
|
||||
return null;
|
||||
}
|
||||
range = range.trim();
|
||||
if (!range.startsWith("bytes=")) {
|
||||
return null;
|
||||
}
|
||||
String rangeValue = range.substring("bytes=".length()).trim();
|
||||
int separatorIndex = rangeValue.indexOf('-');
|
||||
// 当前实现只接受单个字节范围,不处理 multipart/byteranges
|
||||
if (separatorIndex < 0 || rangeValue.indexOf(',', separatorIndex + 1) != -1) {
|
||||
resp.setHeader("Content-Range", "bytes */" + total);
|
||||
resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||
return null;
|
||||
}
|
||||
String startText = rangeValue.substring(0, separatorIndex).trim();
|
||||
String endText = rangeValue.substring(separatorIndex + 1).trim();
|
||||
if (total <= 0) {
|
||||
resp.setHeader("Content-Range", "bytes */" + total);
|
||||
resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||
return null;
|
||||
}
|
||||
long start;
|
||||
long end;
|
||||
try {
|
||||
if (TimiJava.isEmpty(startText)) {
|
||||
if (TimiJava.isEmpty(endText)) {
|
||||
resp.setHeader("Content-Range", "bytes */" + total);
|
||||
resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||
return null;
|
||||
}
|
||||
// `bytes=-500` 表示请求文件末尾 500 字节
|
||||
long suffixLength = Long.parseLong(endText);
|
||||
if (suffixLength <= 0) {
|
||||
resp.setHeader("Content-Range", "bytes */" + total);
|
||||
resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||
return null;
|
||||
}
|
||||
start = Math.max(0, total - suffixLength);
|
||||
end = total - 1;
|
||||
} else {
|
||||
// `bytes=97043805-` 表示从指定起点一直读到文件结尾
|
||||
start = Long.parseLong(startText);
|
||||
end = TimiJava.isEmpty(endText) ? total - 1 : Long.parseLong(endText);
|
||||
}
|
||||
} catch (NumberFormatException exception) {
|
||||
resp.setHeader("Content-Range", "bytes */" + total);
|
||||
resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||
return null;
|
||||
}
|
||||
// 处理 bytes=0-999 格式
|
||||
String rangeValue = range.substring("bytes=".length());
|
||||
String[] ranges = rangeValue.split("-");
|
||||
TimiException.requiredTrue(2 == ranges.length, "Invalid Range format");
|
||||
long start = Long.parseLong(ranges[0]);
|
||||
long end = ranges[1].isEmpty() ? total - 1 : Long.parseLong(ranges[1]);
|
||||
// 验证范围有效性
|
||||
if (start < 0 || total <= end || end < start) {
|
||||
resp.setHeader("Content-Range", "bytes */" + total);
|
||||
@@ -463,6 +512,9 @@ public class TimiSpring {
|
||||
public static void responseRangeStream(InputStream stream, long total) throws IOException {
|
||||
HttpServletResponse resp = getResponse();
|
||||
RequestRange range = getRequestRange(total);
|
||||
if (range == null && resp.isCommitted()) {
|
||||
return;
|
||||
}
|
||||
if (range == null) {
|
||||
// 完整文件
|
||||
resp.setContentLengthLong(total);
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.imyeyu.spring.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 标记需要在响应阶段自动回填的多语言字段
|
||||
*
|
||||
* @author 夜雨
|
||||
* @since 2026-07-17 00:00
|
||||
*/
|
||||
@Target({ElementType.FIELD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface MultilingualField {
|
||||
|
||||
/**
|
||||
* 多语言 ID 来源字段名
|
||||
*
|
||||
* @return 来源字段名
|
||||
*/
|
||||
String value();
|
||||
|
||||
/**
|
||||
* 模板参数来源字段名
|
||||
*
|
||||
* @return 同类中的 Map 字段名
|
||||
*/
|
||||
String argMap() default "";
|
||||
}
|
||||
@@ -3,8 +3,8 @@ package com.imyeyu.spring.annotation;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.imyeyu.java.TimiJava;
|
||||
import com.imyeyu.java.bean.timi.TimiCode;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.java.bean.ResultCode;
|
||||
import com.imyeyu.java.bean.ActionException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.lang.NonNull;
|
||||
@@ -48,7 +48,7 @@ public class RequestBodyValueArgumentResolver implements HandlerMethodArgumentRe
|
||||
return null;
|
||||
}
|
||||
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
|
||||
TimiException.required(request, "not found request");
|
||||
ActionException.required(request, "not found request");
|
||||
assert request != null;
|
||||
|
||||
JsonNode requestBody;
|
||||
@@ -58,9 +58,9 @@ public class RequestBodyValueArgumentResolver implements HandlerMethodArgumentRe
|
||||
return jsonNode;
|
||||
}
|
||||
byte[] bodyBytes = request.getInputStream().readAllBytes();
|
||||
TimiException.requiredTrue(1 < bodyBytes.length, "empty request body");
|
||||
ActionException.requiredTrue(1 < bodyBytes.length, "empty request body");
|
||||
requestBody = objectMapper.readTree(bodyBytes);
|
||||
TimiException.requiredTrue(requestBody != null && requestBody.isObject(), "not object request body");
|
||||
ActionException.requiredTrue(requestBody != null && requestBody.isObject(), "not object request body");
|
||||
request.setAttribute(REQUEST_BODY_JSON_NODE_ATTR, requestBody);
|
||||
}
|
||||
String fieldName = bodyValue.value();
|
||||
@@ -68,14 +68,14 @@ public class RequestBodyValueArgumentResolver implements HandlerMethodArgumentRe
|
||||
if (TimiJava.isEmpty(fieldName)) {
|
||||
fieldName = parameter.getParameterName();
|
||||
}
|
||||
TimiException.required(fieldName, "not found @RequestBodyValue parameter name");
|
||||
ActionException.required(fieldName, "not found @RequestBodyValue parameter name");
|
||||
}
|
||||
JsonNode fieldNode = requestBody.get(fieldName);
|
||||
if (fieldNode == null || fieldNode.isMissingNode() || fieldNode.isNull()) {
|
||||
if (!bodyValue.required()) {
|
||||
return null;
|
||||
}
|
||||
throw new TimiException(TimiCode.ARG_MISS, "not found json field: %s".formatted(fieldName));
|
||||
throw new ActionException(ResultCode.ARG_MISS, "not found json field: %s".formatted(fieldName));
|
||||
}
|
||||
return objectMapper.treeToValue(fieldNode, parameter.getParameterType());
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import java.lang.annotation.Target;
|
||||
/**
|
||||
* 应用在 Controller 的接口上
|
||||
*
|
||||
* <p>{@link #lifeCycle()} 生命周期内(秒)限制访问 {@link #value()} 次
|
||||
* <p>{@link #inSeconds()} 生命周期内(秒)限制访问 {@link #value()} 次
|
||||
*
|
||||
* @author 夜雨
|
||||
* @version 2021-08-16 17:57
|
||||
@@ -32,5 +32,5 @@ public @interface RequestRateLimit {
|
||||
*
|
||||
* @return 生命周期秒数
|
||||
*/
|
||||
int lifeCycle() default 10;
|
||||
int inSeconds() default 10;
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ public abstract class RequestRateLimitAbstractInterceptor implements HandlerInte
|
||||
return true;
|
||||
}
|
||||
// 频率限制
|
||||
return beforeRun(req, resp, buildId(handlerMethod), requestRateLimit.lifeCycle(), requestRateLimit.value());
|
||||
return beforeRun(req, resp, buildId(handlerMethod), requestRateLimit.inSeconds(), requestRateLimit.value());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -37,34 +37,6 @@ public class Page<T> extends BasePage {
|
||||
/** 排序字段映射 */
|
||||
protected LinkedHashMap<String, BaseMapper.OrderType> orderMap;
|
||||
|
||||
/**
|
||||
* 创建分页参数
|
||||
*
|
||||
* @param index 页码
|
||||
* @param size 每页数量
|
||||
*/
|
||||
public Page(int index, int size) {
|
||||
super(index, size);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取偏移量
|
||||
*
|
||||
* @return 偏移量
|
||||
*/
|
||||
public long getOffset() {
|
||||
return (long) index * size;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取限制数量
|
||||
*
|
||||
* @return 限制数量
|
||||
*/
|
||||
public long getLimit() {
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加排序字段
|
||||
*
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.imyeyu.spring.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
import com.imyeyu.spring.annotation.table.DeleteColumn;
|
||||
import com.imyeyu.spring.util.ResponseView;
|
||||
import com.imyeyu.utils.Time;
|
||||
import lombok.Data;
|
||||
|
||||
@@ -16,15 +18,19 @@ import java.io.Serializable;
|
||||
public class BaseEntity implements Serializable, Creatable, Updatable, Deletable {
|
||||
|
||||
/** 创建时间 */
|
||||
@JsonView(ResponseView.Public.class)
|
||||
protected Long createdAt;
|
||||
|
||||
/** 更新时间 */
|
||||
@JsonView(ResponseView.Public.class)
|
||||
protected Long updatedAt;
|
||||
|
||||
/** 删除时间 */
|
||||
@DeleteColumn
|
||||
@JsonView(ResponseView.Admin.class)
|
||||
protected Long deletedAt;
|
||||
|
||||
@JsonView(ResponseView.Admin.class)
|
||||
@Override
|
||||
public boolean isDeleted() {
|
||||
return deletedAt != null && deletedAt < Time.now();
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.imyeyu.spring.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
import com.imyeyu.spring.annotation.table.Id;
|
||||
import com.imyeyu.spring.util.ResponseView;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@@ -16,5 +18,6 @@ public class Entity extends BaseEntity implements IDEntity<Long> {
|
||||
|
||||
/** ID */
|
||||
@Id
|
||||
@JsonView(ResponseView.Public.class)
|
||||
protected Long id;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package com.imyeyu.spring.entity;
|
||||
|
||||
import com.imyeyu.java.bean.Language;
|
||||
import com.imyeyu.java.ref.Ref;
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
import com.imyeyu.lang.bean.Language;
|
||||
import com.imyeyu.lang.bean.MultilingualValue;
|
||||
import com.imyeyu.spring.annotation.table.AutoUUID;
|
||||
import com.imyeyu.spring.annotation.table.Id;
|
||||
import com.imyeyu.spring.util.ResponseView;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@@ -15,36 +17,27 @@ import lombok.EqualsAndHashCode;
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class Multilingual extends Language implements IDEntity<String>, Creatable, Updatable, Deletable, Destroyable {
|
||||
public class Multilingual extends Language implements MultilingualValue, IDEntity<String>, Creatable, Updatable, Deletable, Destroyable {
|
||||
|
||||
/** 唯一标识 */
|
||||
@Id
|
||||
@AutoUUID
|
||||
@JsonView(ResponseView.Public.class)
|
||||
protected String id;
|
||||
|
||||
/** 业务类型 */
|
||||
@JsonView(ResponseView.Public.class)
|
||||
protected String bizType;
|
||||
|
||||
/** 创建时间 */
|
||||
@JsonView(ResponseView.Admin.class)
|
||||
protected Long createdAt;
|
||||
|
||||
/** 更新时间 */
|
||||
@JsonView(ResponseView.Admin.class)
|
||||
protected Long updatedAt;
|
||||
|
||||
/** 删除时间 */
|
||||
@JsonView(ResponseView.Admin.class)
|
||||
protected Long deletedAt;
|
||||
|
||||
/**
|
||||
* 获取指定语言值
|
||||
*
|
||||
* @param language 指定语言
|
||||
* @return 值
|
||||
*/
|
||||
public String getValue(Language.Enum language) {
|
||||
try {
|
||||
return Ref.getFieldValue(this, language.toString().replace("_", ""), String.class);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package com.imyeyu.spring.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
import com.imyeyu.spring.annotation.table.AutoUUID;
|
||||
import com.imyeyu.spring.annotation.table.Id;
|
||||
import com.imyeyu.spring.util.ResponseView;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@@ -18,5 +20,6 @@ public class UUIDEntity extends BaseEntity implements IDEntity<String> {
|
||||
/** ID */
|
||||
@Id
|
||||
@AutoUUID
|
||||
@JsonView(ResponseView.Public.class)
|
||||
protected String id;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.imyeyu.spring.service;
|
||||
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.java.bean.ActionException;
|
||||
import com.imyeyu.spring.bean.Page;
|
||||
import com.imyeyu.spring.bean.PageResult;
|
||||
import com.imyeyu.spring.entity.Deletable;
|
||||
@@ -32,7 +32,7 @@ public abstract class AbstractEntityService<T, P> implements BaseService<T, P> {
|
||||
if (baseMapper == null) {
|
||||
baseMapper = mapper();
|
||||
}
|
||||
TimiException.required(baseMapper, "mapper() can not be null");
|
||||
ActionException.required(baseMapper, "mapper() can not be null");
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.imyeyu.spring.service;
|
||||
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.java.bean.ActionException;
|
||||
|
||||
/**
|
||||
* 可创建实体服务
|
||||
@@ -15,7 +15,7 @@ public interface CreatableService<T> {
|
||||
* 创建数据
|
||||
*
|
||||
* @param t 数据对象
|
||||
* @throws TimiException 服务异常
|
||||
* @throws ActionException 服务异常
|
||||
*/
|
||||
void create(T t);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.imyeyu.spring.service;
|
||||
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.java.bean.ActionException;
|
||||
|
||||
/**
|
||||
* 可软删除实体服务
|
||||
@@ -15,7 +15,7 @@ public interface DeletableService<P> {
|
||||
* 软删除
|
||||
*
|
||||
* @param p 数据对象
|
||||
* @throws TimiException 服务异常
|
||||
* @throws ActionException 服务异常
|
||||
*/
|
||||
void delete(P p);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.imyeyu.spring.service;
|
||||
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.java.bean.ActionException;
|
||||
|
||||
/**
|
||||
* 可销毁(物理删除)实体服务
|
||||
@@ -15,7 +15,7 @@ public interface DestroyableService<P> {
|
||||
* 销毁(物理删除)
|
||||
*
|
||||
* @param p 数据对象
|
||||
* @throws TimiException 服务异常
|
||||
* @throws ActionException 服务异常
|
||||
*/
|
||||
void destroy(P p);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.imyeyu.spring.service;
|
||||
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.java.bean.ActionException;
|
||||
|
||||
/**
|
||||
* 可更新实体服务
|
||||
@@ -15,7 +15,7 @@ public interface UpdatableService<T> {
|
||||
* 修改数据
|
||||
*
|
||||
* @param t 数据对象
|
||||
* @throws TimiException 服务异常
|
||||
* @throws ActionException 服务异常
|
||||
*/
|
||||
void update(T t);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@ package com.imyeyu.spring.util;
|
||||
|
||||
import com.imyeyu.java.TimiJava;
|
||||
import com.imyeyu.java.bean.CallbackArgReturn;
|
||||
import com.imyeyu.java.bean.timi.TimiCode;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.java.bean.ResultCode;
|
||||
import com.imyeyu.java.bean.ActionException;
|
||||
import com.imyeyu.java.ref.Ref;
|
||||
import com.imyeyu.spring.annotation.table.AutoUUID;
|
||||
import com.imyeyu.spring.annotation.table.Column;
|
||||
@@ -31,6 +31,7 @@ import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -81,6 +82,21 @@ public abstract class BaseSQLProvider {
|
||||
* @return SQL
|
||||
*/
|
||||
protected String buildSelectByPageSQL(EntityMeta meta, String tableName, Page<?> page, String offset, String limit) {
|
||||
return buildSelectByPageSQL(meta, tableName, page, offset, limit, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建分页查询 SQL
|
||||
*
|
||||
* @param meta 实体元数据
|
||||
* @param tableName 表名
|
||||
* @param page 分页参数
|
||||
* @param offset 偏移量占位符
|
||||
* @param limit 限制数量占位符
|
||||
* @param pageParameterPath Page 参数路径前缀
|
||||
* @return SQL
|
||||
*/
|
||||
protected String buildSelectByPageSQL(EntityMeta meta, String tableName, Page<?> page, String offset, String limit, String pageParameterPath) {
|
||||
StringBuilder sql = new StringBuilder();
|
||||
sql.append("SELECT %s FROM `%s` WHERE 1 = 1".formatted(meta.selectPageClause, tableName));
|
||||
|
||||
@@ -88,7 +104,11 @@ public abstract class BaseSQLProvider {
|
||||
appendSoftDeleteCondition(sql, meta);
|
||||
|
||||
// 添加 Page 查询条件
|
||||
appendPageConditions(sql, page);
|
||||
if (pageParameterPath.isEmpty()) {
|
||||
appendPageConditions(sql, page);
|
||||
} else {
|
||||
appendPageConditions(sql, page, pageParameterPath);
|
||||
}
|
||||
|
||||
// 添加排序
|
||||
appendOrderBy(sql, meta, page);
|
||||
@@ -107,6 +127,19 @@ public abstract class BaseSQLProvider {
|
||||
* @return SQL
|
||||
*/
|
||||
protected String buildCountByPageSQL(EntityMeta meta, String tableName, Page<?> page) {
|
||||
return buildCountByPageSQL(meta, tableName, page, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建分页统计 SQL
|
||||
*
|
||||
* @param meta 实体元数据
|
||||
* @param tableName 表名
|
||||
* @param page 分页参数
|
||||
* @param pageParameterPath Page 参数路径前缀
|
||||
* @return SQL
|
||||
*/
|
||||
protected String buildCountByPageSQL(EntityMeta meta, String tableName, Page<?> page, String pageParameterPath) {
|
||||
StringBuilder sql = new StringBuilder();
|
||||
sql.append("SELECT COUNT(*) FROM `%s` WHERE 1 = 1".formatted(tableName));
|
||||
|
||||
@@ -114,7 +147,11 @@ public abstract class BaseSQLProvider {
|
||||
appendSoftDeleteCondition(sql, meta);
|
||||
|
||||
// 添加 Page 查询条件
|
||||
appendPageConditions(sql, page);
|
||||
if (pageParameterPath.isEmpty()) {
|
||||
appendPageConditions(sql, page);
|
||||
} else {
|
||||
appendPageConditions(sql, page, pageParameterPath);
|
||||
}
|
||||
|
||||
return sql.toString();
|
||||
}
|
||||
@@ -138,30 +175,82 @@ public abstract class BaseSQLProvider {
|
||||
* @param page 分页参数
|
||||
*/
|
||||
protected void appendPageConditions(StringBuilder sql, Page<?> page) {
|
||||
appendPageConditions(sql, page, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加 Page 查询条件
|
||||
*
|
||||
* @param sql SQL 构建器
|
||||
* @param page 分页参数
|
||||
* @param pageParameterPath Page 参数路径前缀
|
||||
*/
|
||||
protected void appendPageConditions(StringBuilder sql, Page<?> page, String pageParameterPath) {
|
||||
// 精准查询
|
||||
if (TimiJava.isNotEmpty(page.getEqualsExample())) {
|
||||
Object obj = page.getEqualsExample();
|
||||
EntityMeta metaExample = getEntityMeta(obj.getClass());
|
||||
String conditionClause = metaExample.fieldColumnList.stream()
|
||||
.filter(fc -> fc.isNotEmpty(obj))
|
||||
.map(fc -> "`%s` = '%s'".formatted(fc.columnName, fc.getAsString(obj)))
|
||||
.collect(Collectors.joining(" %s ".formatted(page.getEqualsLogic())));
|
||||
if (TimiJava.isNotEmpty(conditionClause)) {
|
||||
sql.append(" AND ").append(conditionClause);
|
||||
}
|
||||
}
|
||||
appendPageExampleConditions(
|
||||
sql,
|
||||
page.getEqualsExample(),
|
||||
page.getEqualsLogic(),
|
||||
false,
|
||||
pageParameterPath
|
||||
);
|
||||
|
||||
// 模糊查询
|
||||
if (TimiJava.isNotEmpty(page.getLikesExample())) {
|
||||
Object obj = page.getLikesExample();
|
||||
EntityMeta metaExample = getEntityMeta(obj.getClass());
|
||||
String conditionClause = metaExample.fieldColumnList.stream()
|
||||
.filter(fc -> fc.isNotEmpty(obj))
|
||||
.map(fc -> "`%s` LIKE CONCAT('%%', '%s', '%%')".formatted(fc.columnName, fc.getAsString(obj)))
|
||||
.collect(Collectors.joining(" %s ".formatted(page.getLikesLogic())));
|
||||
if (TimiJava.isNotEmpty(conditionClause)) {
|
||||
sql.append(" AND (").append(conditionClause).append(')');
|
||||
}
|
||||
appendPageExampleConditions(
|
||||
sql,
|
||||
page.getLikesExample(),
|
||||
page.getLikesLogic(),
|
||||
true,
|
||||
pageParameterPath
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一组 Page 示例条件
|
||||
*
|
||||
* @param sql SQL 构建器
|
||||
* @param example 示例对象
|
||||
* @param logic 条件连接逻辑
|
||||
* @param likes 是否使用模糊匹配
|
||||
* @param pageParameterPath Page 参数路径前缀
|
||||
*/
|
||||
private void appendPageExampleConditions(StringBuilder sql, Object example, Logic logic, boolean likes, String pageParameterPath) {
|
||||
if (TimiJava.isEmpty(example)) {
|
||||
return;
|
||||
}
|
||||
EntityMeta metaExample = getEntityMeta(example.getClass());
|
||||
String parameterPrefix = "%s%s.".formatted(pageParameterPath, likes ? "likesExample" : "equalsExample");
|
||||
String conditionClause = metaExample.fieldColumnList.stream()
|
||||
.map(fc -> buildPageCondition(fc, example, likes, parameterPrefix))
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.joining(" %s ".formatted(logic == null ? Logic.AND : logic)));
|
||||
if (TimiJava.isNotEmpty(conditionClause)) {
|
||||
sql.append(" AND (").append(conditionClause).append(')');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建单个 Page 示例条件
|
||||
*
|
||||
* @param fieldColumn 字段元数据
|
||||
* @param example 示例对象
|
||||
* @param likes 是否使用模糊匹配
|
||||
* @param parameterPrefix 参数路径前缀
|
||||
* @return 条件子句;字段值为空时返回 null
|
||||
*/
|
||||
private String buildPageCondition(FieldColumn fieldColumn, Object example, boolean likes, String parameterPrefix) {
|
||||
Object value = fieldColumn.getValue(example);
|
||||
if (TimiJava.isEmpty(value)) {
|
||||
return null;
|
||||
}
|
||||
if (value instanceof Boolean booleanValue) {
|
||||
return "`%s` IS %s".formatted(fieldColumn.columnName, booleanValue ? "TRUE" : "FALSE");
|
||||
}
|
||||
String parameter = "#{%s%s}".formatted(parameterPrefix, fieldColumn.fieldName);
|
||||
if (likes) {
|
||||
return "`%s` LIKE CONCAT('%%', %s, '%%')".formatted(fieldColumn.columnName, parameter);
|
||||
}
|
||||
return "`%s` = %s".formatted(fieldColumn.columnName, parameter);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -231,7 +320,7 @@ public abstract class BaseSQLProvider {
|
||||
Ref.setFieldValue(entity, fc.field, uuid);
|
||||
}
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new TimiException(TimiCode.ERROR).msgKey("auto set field:%s value error".formatted(fc.fieldName));
|
||||
throw new ActionException(ResultCode.ERROR, "auto set field:%s value error".formatted(fc.fieldName));
|
||||
}
|
||||
if (entity instanceof Creatable creatableEntity && creatableEntity.getCreatedAt() == null) {
|
||||
creatableEntity.setCreatedAt(Time.now());
|
||||
@@ -250,7 +339,7 @@ public abstract class BaseSQLProvider {
|
||||
* @return SQL
|
||||
*/
|
||||
protected String buildSelectByIdSQL(EntityMeta meta, String tableName, String idParam) {
|
||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
|
||||
StringBuilder sql = new StringBuilder();
|
||||
sql.append("SELECT %s FROM `%s` WHERE `%s` = #{%s}".formatted(
|
||||
@@ -299,8 +388,8 @@ public abstract class BaseSQLProvider {
|
||||
* @return SQL
|
||||
*/
|
||||
protected String buildUpdateSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix) {
|
||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
TimiException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
|
||||
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
ActionException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
|
||||
|
||||
if (entity instanceof Updatable updatable) {
|
||||
updatable.setUpdatedAt(Time.now());
|
||||
@@ -328,8 +417,8 @@ public abstract class BaseSQLProvider {
|
||||
* @return SQL
|
||||
*/
|
||||
protected String buildUpdateSelectiveSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix) {
|
||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
TimiException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
|
||||
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
ActionException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
|
||||
|
||||
if (entity instanceof Updatable updatable) {
|
||||
updatable.setUpdatedAt(Time.now());
|
||||
@@ -357,8 +446,8 @@ public abstract class BaseSQLProvider {
|
||||
* @return SQL
|
||||
*/
|
||||
protected String buildDeleteSQL(EntityMeta meta, String tableName, String idParam) {
|
||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
TimiException.requiredTrue(meta.canDelete, "not allow soft delete for %s".formatted(meta.entityClass));
|
||||
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
ActionException.requiredTrue(meta.canDelete, "not allow soft delete for %s".formatted(meta.entityClass));
|
||||
|
||||
return "UPDATE `%s` SET `deleted_at` = %s WHERE `%s` = #{%s}".formatted(
|
||||
tableName,
|
||||
@@ -379,13 +468,13 @@ public abstract class BaseSQLProvider {
|
||||
* @return SQL
|
||||
*/
|
||||
protected String buildDeleteAllByExampleSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix, Logic logic) {
|
||||
TimiException.required(meta.canDelete, "not allow delete for %s".formatted(meta.entityClass));
|
||||
ActionException.required(meta.canDelete, "not allow delete for %s".formatted(meta.entityClass));
|
||||
|
||||
FieldColumn deleteColumn = meta.getFieldColumnList().stream()
|
||||
.filter(fc -> fc.isDeleteColumn)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
TimiException.required(deleteColumn, "unknown delete column, use com.imyeyu.spring.annotation.table.DeleteColumn annotation on field");
|
||||
ActionException.required(deleteColumn, "unknown delete column, use com.imyeyu.spring.annotation.table.DeleteColumn annotation on field");
|
||||
assert deleteColumn != null;
|
||||
assert deleteColumn.deleteColumnType != null;
|
||||
|
||||
@@ -412,8 +501,8 @@ public abstract class BaseSQLProvider {
|
||||
* @return SQL
|
||||
*/
|
||||
protected String buildDestroySQL(EntityMeta meta, String tableName, String idParam) {
|
||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
TimiException.requiredTrue(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
|
||||
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
ActionException.requiredTrue(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
|
||||
|
||||
return "DELETE FROM `%s` WHERE `%s` = #{%s}".formatted(tableName, meta.idFieldColumn.columnName, idParam);
|
||||
}
|
||||
@@ -429,7 +518,7 @@ public abstract class BaseSQLProvider {
|
||||
* @return SQL
|
||||
*/
|
||||
protected String buildDestroyAllByExampleSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix, Logic logic) {
|
||||
TimiException.required(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
|
||||
ActionException.required(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
|
||||
String destroyClause = meta.fieldColumnList.stream()
|
||||
.filter(FieldColumn::isNotId)
|
||||
.filter(fc -> fc.isNotEmpty(entity))
|
||||
@@ -494,7 +583,7 @@ public abstract class BaseSQLProvider {
|
||||
this.table = Text.camelCase2underscore(entityClass.getSimpleName());
|
||||
} else {
|
||||
this.table = table.value();
|
||||
TimiException.required(this.table, String.format("empty table annotation value for %s entity", entityClass.getName()));
|
||||
ActionException.required(this.table, String.format("empty table annotation value for %s entity", entityClass.getName()));
|
||||
}
|
||||
List<Field> allFieldList = Ref.listAllFields(entityClass);
|
||||
FieldColumn idFieldColumn = null;
|
||||
@@ -506,7 +595,7 @@ public abstract class BaseSQLProvider {
|
||||
}
|
||||
FieldColumn fieldColumn = new FieldColumn(field);
|
||||
if (fieldColumn.isId) {
|
||||
TimiException.requiredNull(idFieldColumn, String.format("multi id field for %s entity", entityClass.getName()));
|
||||
ActionException.requiredNull(idFieldColumn, String.format("multi id field for %s entity", entityClass.getName()));
|
||||
idFieldColumn = fieldColumn;
|
||||
}
|
||||
fieldColumnList.add(fieldColumn);
|
||||
@@ -624,7 +713,7 @@ public abstract class BaseSQLProvider {
|
||||
columnName = Text.camelCase2underscore(field.getName());
|
||||
} else {
|
||||
columnName = column.value();
|
||||
TimiException.required(columnName, "empty field:%s column annotation value for %s entity".formatted(field.getName(), field.getDeclaringClass()));
|
||||
ActionException.required(columnName, "empty field:%s column annotation value for %s entity".formatted(field.getName(), field.getDeclaringClass()));
|
||||
}
|
||||
isId = field.isAnnotationPresent(Id.class);
|
||||
isAutoUUID = field.isAnnotationPresent(AutoUUID.class);
|
||||
@@ -648,11 +737,7 @@ public abstract class BaseSQLProvider {
|
||||
* @return true 为 null
|
||||
*/
|
||||
public boolean isNull(Object entity) {
|
||||
try {
|
||||
return Ref.getFieldValue(entity, field, Object.class) == null;
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return getValue(entity) == null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -672,11 +757,7 @@ public abstract class BaseSQLProvider {
|
||||
* @return true 为空
|
||||
*/
|
||||
public boolean isEmpty(Object entity) {
|
||||
try {
|
||||
return TimiJava.isEmpty(Ref.getFieldValue(entity, field, Object.class));
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return TimiJava.isEmpty(getValue(entity));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -696,8 +777,18 @@ public abstract class BaseSQLProvider {
|
||||
* @return 字符串值
|
||||
*/
|
||||
public String getAsString(Object obj) {
|
||||
return getValue(obj).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取字段值
|
||||
*
|
||||
* @param entity 实体
|
||||
* @return 字段值
|
||||
*/
|
||||
public Object getValue(Object entity) {
|
||||
try {
|
||||
return field.get(obj).toString();
|
||||
return Ref.getFieldValue(entity, field, Object.class);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ public class DynamicTableSQLProvider extends BaseSQLProvider {
|
||||
*/
|
||||
public String selectByPage(ProviderContext context, @Param("tableName") String tableName, @Param("page") Page<?> page) {
|
||||
EntityMeta meta = getEntityMeta(context);
|
||||
return buildSelectByPageSQL(meta, tableName, page, "#{page.offset}", "#{page.limit}");
|
||||
return buildSelectByPageSQL(meta, tableName, page, "#{page.offset}", "#{page.limit}", "page.");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -38,7 +38,7 @@ public class DynamicTableSQLProvider extends BaseSQLProvider {
|
||||
*/
|
||||
public String countByPage(ProviderContext context, @Param("tableName") String tableName, @Param("page") Page<?> page) {
|
||||
EntityMeta meta = getEntityMeta(context);
|
||||
return buildCountByPageSQL(meta, tableName, page);
|
||||
return buildCountByPageSQL(meta, tableName, page, "page.");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
package com.imyeyu.spring.util;
|
||||
|
||||
import com.imyeyu.java.bean.timi.TimiCode;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.java.bean.timi.TimiResponse;
|
||||
import com.imyeyu.java.TimiJava;
|
||||
import com.imyeyu.java.bean.ActionError;
|
||||
import com.imyeyu.java.bean.ActionException;
|
||||
import com.imyeyu.java.bean.Response;
|
||||
import com.imyeyu.java.bean.ResultCode;
|
||||
import com.imyeyu.lang.MultilingualResolver;
|
||||
import com.imyeyu.spring.TimiSpring;
|
||||
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.validation.ValidationException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.TypeMismatchException;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.converter.HttpMessageConversionException;
|
||||
import org.springframework.validation.BindException;
|
||||
@@ -27,10 +34,15 @@ public class GlobalExceptionHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
private final ObjectProvider<MultilingualResolver> multilingualResolverProvider;
|
||||
|
||||
/**
|
||||
* 创建全局异常处理器
|
||||
*
|
||||
* @param multilingualResolverProvider 消息解析器提供器
|
||||
*/
|
||||
public GlobalExceptionHandler() {
|
||||
public GlobalExceptionHandler(ObjectProvider<MultilingualResolver> multilingualResolverProvider) {
|
||||
this.multilingualResolverProvider = multilingualResolverProvider;
|
||||
}
|
||||
|
||||
@Value("${spring.profiles.active}")
|
||||
@@ -42,13 +54,17 @@ public class GlobalExceptionHandler {
|
||||
* @param e 异常
|
||||
* @return 异常返回
|
||||
*/
|
||||
@IgnoreGlobalReturn
|
||||
@ExceptionHandler(HttpMessageConversionException.class)
|
||||
public TimiResponse<?> conversionException(HttpMessageConversionException e) {
|
||||
public Object conversionException(HttpMessageConversionException e) {
|
||||
log.warn(e.getMessage());
|
||||
if (env.contains("dev") || log.isDebugEnabled()) {
|
||||
log.error("conversion error", e);
|
||||
}
|
||||
return new TimiResponse<>(TimiCode.ARG_BAD).msgKey("invalid.body");
|
||||
if (ignoreCommittedBinaryResponse()) {
|
||||
return null;
|
||||
}
|
||||
return fail(ResultCode.ARG_BAD, "invalid.body");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -57,13 +73,17 @@ public class GlobalExceptionHandler {
|
||||
* @param e 异常
|
||||
* @return 异常返回
|
||||
*/
|
||||
@IgnoreGlobalReturn
|
||||
@ExceptionHandler(ServletException.class)
|
||||
public TimiResponse<?> headerException(ServletException e) {
|
||||
public Object headerException(ServletException e) {
|
||||
log.warn(e.getMessage());
|
||||
if (env.contains("dev") || log.isDebugEnabled()) {
|
||||
log.error("header error", e);
|
||||
}
|
||||
return new TimiResponse<>(TimiCode.REQUEST_BAD).msgKey("invalid.request");
|
||||
if (ignoreCommittedBinaryResponse()) {
|
||||
return null;
|
||||
}
|
||||
return fail(ResultCode.REQUEST_BAD, "invalid.request");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -72,19 +92,20 @@ public class GlobalExceptionHandler {
|
||||
* @param e 异常
|
||||
* @return 异常返回
|
||||
*/
|
||||
@IgnoreGlobalReturn
|
||||
@ExceptionHandler({BindException.class, ValidationException.class, MethodArgumentNotValidException.class, TypeMismatchException.class})
|
||||
public TimiResponse<?> paramsException(Exception e) {
|
||||
public Response<?> paramsException(Exception e) {
|
||||
if (e instanceof MethodArgumentNotValidException subE) {
|
||||
log.warn("request error", e);
|
||||
FieldError error = subE.getBindingResult().getFieldError();
|
||||
if (error != null) {
|
||||
return new TimiResponse<>(TimiCode.ARG_BAD, "[%s] %s".formatted(error.getField(), error.getDefaultMessage()));
|
||||
return fail(ResultCode.ARG_BAD, "[%s] %s".formatted(error.getField(), error.getDefaultMessage()));
|
||||
}
|
||||
}
|
||||
if (env.startsWith("dev") || log.isDebugEnabled()) {
|
||||
log.error("request error", e);
|
||||
}
|
||||
return new TimiResponse<>(TimiCode.REQUEST_BAD).msgKey("invalid.arg");
|
||||
return fail(ResultCode.REQUEST_BAD, "invalid.arg");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,17 +114,112 @@ public class GlobalExceptionHandler {
|
||||
* @param e 异常
|
||||
* @return 异常返回
|
||||
*/
|
||||
@IgnoreGlobalReturn
|
||||
@ExceptionHandler(Throwable.class)
|
||||
public TimiResponse<?> error(Throwable e) {
|
||||
if (e instanceof TimiException timiE) {
|
||||
public Object error(Throwable e) {
|
||||
if (e instanceof ActionException timiE) {
|
||||
if (!env.startsWith("prod") || log.isDebugEnabled()) {
|
||||
log.error(timiE.getMessage(), e);
|
||||
}
|
||||
// 一般异常
|
||||
return timiE.toResponse();
|
||||
if (ignoreCommittedBinaryResponse()) {
|
||||
return null;
|
||||
}
|
||||
return fail(timiE);
|
||||
}
|
||||
if (e instanceof ActionError actionE) {
|
||||
log.error(actionE.getMessage(), e);
|
||||
if (ignoreCommittedBinaryResponse()) {
|
||||
return null;
|
||||
}
|
||||
return fail(actionE.getCode(), actionE.getMessageCode(), actionE.getMessageArgs());
|
||||
}
|
||||
// 致命异常
|
||||
log.error("fatal error", e);
|
||||
return new TimiResponse<>(TimiCode.ERROR).msgKey("service.error");
|
||||
if (ignoreCommittedBinaryResponse()) {
|
||||
return null;
|
||||
}
|
||||
return fail(ResultCode.ERROR, "service.error");
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建失败响应
|
||||
*
|
||||
* @param e 异常
|
||||
* @return 响应
|
||||
*/
|
||||
private Response<?> fail(ActionException e) {
|
||||
return fail(e.getCode(), e.getMessageCode(), e.getMessageArgs());
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建失败响应
|
||||
*
|
||||
* @param code 代码
|
||||
* @param messageCode 消息代码
|
||||
* @return 响应
|
||||
*/
|
||||
private Response<?> fail(ResultCode code, String messageCode) {
|
||||
return fail(code, messageCode, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建失败响应
|
||||
*
|
||||
* @param code 代码
|
||||
* @param messageCode 消息代码
|
||||
* @param messageArgs 消息插值参数
|
||||
* @return 响应
|
||||
*/
|
||||
private Response<?> fail(ResultCode code, String messageCode, java.util.Map<String, Object> messageArgs) {
|
||||
Response<?> result = new Response<>(code).messageCode(messageCode, messageArgs);
|
||||
result.setMessage(resolveMessage(code, messageCode, messageArgs));
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析消息
|
||||
*
|
||||
* @param code 代码
|
||||
* @param messageCode 消息代码
|
||||
* @param messageArgs 消息插值参数
|
||||
* @return 消息
|
||||
*/
|
||||
private String resolveMessage(ResultCode code, String messageCode, java.util.Map<String, Object> messageArgs) {
|
||||
if (TimiJava.isEmpty(messageCode)) {
|
||||
return code.toString();
|
||||
}
|
||||
try {
|
||||
MultilingualResolver messageResolver = multilingualResolverProvider.getIfAvailable();
|
||||
if (messageResolver == null) {
|
||||
return messageCode;
|
||||
}
|
||||
String message = messageResolver.map(TimiSpring.getLanguage()).message(messageCode, messageArgs);
|
||||
return TimiJava.isEmpty(message) ? messageCode : message;
|
||||
} catch (Exception e) {
|
||||
log.error("message resolve error", e);
|
||||
return messageCode;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 已进入二进制响应写出阶段时,不再尝试输出统一 JSON 包装,
|
||||
* 否则只会制造二次异常并覆盖原始状态码。
|
||||
*
|
||||
* @return `true` 表示当前响应应跳过异常包装
|
||||
*/
|
||||
private boolean ignoreCommittedBinaryResponse() {
|
||||
HttpServletResponse response = TimiSpring.getResponse();
|
||||
if (response == null) {
|
||||
return false;
|
||||
}
|
||||
if (response.isCommitted()) {
|
||||
return true;
|
||||
}
|
||||
String contentType = response.getContentType();
|
||||
if (contentType == null || contentType.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String lowerContentType = contentType.toLowerCase();
|
||||
return !lowerContentType.contains("json") && !lowerContentType.startsWith("text/");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
package com.imyeyu.spring.util;
|
||||
|
||||
import com.imyeyu.java.TimiJava;
|
||||
import com.imyeyu.java.bean.CallbackArgReturn;
|
||||
import com.imyeyu.java.bean.LanguageMsgMapping;
|
||||
import com.imyeyu.java.bean.timi.TimiCode;
|
||||
import com.imyeyu.java.bean.timi.TimiResponse;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.imyeyu.java.bean.Response;
|
||||
import com.imyeyu.java.bean.ResultCode;
|
||||
import com.imyeyu.spring.TimiSpring;
|
||||
import com.imyeyu.spring.annotation.AOPLogInterceptor;
|
||||
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
|
||||
import lombok.Data;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.lang.NonNull;
|
||||
@@ -23,24 +22,24 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 全局返回处理器,包装 TimiResponse
|
||||
* 全局返回处理器,包装 Response
|
||||
*
|
||||
* @author 夜雨
|
||||
* @version 2023-04-30 00:59
|
||||
*/
|
||||
@Data
|
||||
@RestControllerAdvice
|
||||
public class GlobalReturnHandler implements ResponseBodyAdvice<Object> {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GlobalReturnHandler.class);
|
||||
|
||||
/** 多语言头处理回调 */
|
||||
private CallbackArgReturn<LanguageMsgMapping<?>, String> multilingualHeader;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* 创建全局返回处理器
|
||||
*
|
||||
* @param objectMapper JSON 对象映射器
|
||||
*/
|
||||
public GlobalReturnHandler() {
|
||||
public GlobalReturnHandler(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -55,27 +54,24 @@ public class GlobalReturnHandler implements ResponseBodyAdvice<Object> {
|
||||
@NonNull MediaType selectedContentType,
|
||||
@NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
|
||||
@NonNull ServerHttpRequest request,
|
||||
@NonNull ServerHttpResponse response)
|
||||
{
|
||||
TimiResponse<?> result;
|
||||
if (body instanceof TimiResponse<?> timiResponse) {
|
||||
// 可能已被全局异常包装
|
||||
result = timiResponse;
|
||||
@NonNull ServerHttpResponse response
|
||||
) {
|
||||
Response<?> result;
|
||||
if (body instanceof Response<?> Response) {
|
||||
result = Response;
|
||||
} else {
|
||||
result = new TimiResponse<>(TimiCode.SUCCESS, body);
|
||||
}
|
||||
try {
|
||||
if (multilingualHeader != null && TimiJava.isNotEmpty(result.getMsgKey())) {
|
||||
result.setMsg(multilingualHeader.handler(result));
|
||||
} else if (TimiJava.isEmpty(result.getMsg())) {
|
||||
result.setMsg(TimiCode.fromCode(result.getCode()).toString());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("multilingual response error", e);
|
||||
result.setMsg(TimiCode.fromCode(result.getCode()).toString());
|
||||
result = new Response<>(ResultCode.SUCCESS, body);
|
||||
}
|
||||
if (30000 < result.getCode()) {
|
||||
log.warn("ID: {} Response -> Exception.{}.{}", TimiSpring.getSessionAttr(AOPLogInterceptor.REQUEST_ID), result.getCode(), result.getMsg());
|
||||
log.warn("ID: {} Response -> Exception.{}.{}", TimiSpring.getSessionAttr(AOPLogInterceptor.REQUEST_ID), result.getCode(), result.getMessage());
|
||||
}
|
||||
if (StringHttpMessageConverter.class.isAssignableFrom(selectedConverterType)) {
|
||||
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
|
||||
try {
|
||||
return objectMapper.writeValueAsString(result);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("统一响应序列化失败", e);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
package com.imyeyu.spring.util;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.imyeyu.java.TimiJava;
|
||||
import com.imyeyu.java.bean.CallbackArgReturn;
|
||||
import com.imyeyu.lang.bean.Language;
|
||||
import com.imyeyu.lang.bean.MultilingualValue;
|
||||
import com.imyeyu.spring.TimiSpring;
|
||||
import com.imyeyu.spring.annotation.MultilingualField;
|
||||
import com.imyeyu.utils.StringInterpolator;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.Reader;
|
||||
import java.io.Writer;
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.nio.file.Path;
|
||||
import java.time.temporal.TemporalAccessor;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 统一回填响应对象中的多语言字段
|
||||
*
|
||||
* @author 夜雨
|
||||
* @since 2026-07-17 00:00
|
||||
*/
|
||||
@Slf4j
|
||||
public class MultilingualFieldBinder {
|
||||
|
||||
private static final StringInterpolator INTERPOLATOR = new StringInterpolator(StringInterpolator.SIMPLE_OBJ);
|
||||
private static final Map<Class<?>, List<Field>> TRAVERSE_CACHE = new ConcurrentHashMap<>();
|
||||
private static final Map<Class<?>, List<BindingField>> BINDING_CACHE = new ConcurrentHashMap<>();
|
||||
|
||||
private final CallbackArgReturn<Collection<String>, ? extends Collection<? extends MultilingualValue>> callback;
|
||||
|
||||
/**
|
||||
* 创建多语言字段回填器
|
||||
*
|
||||
* @param callback 根据多语言 ID 查询多语言值
|
||||
*/
|
||||
public MultilingualFieldBinder(CallbackArgReturn<Collection<String>, ? extends Collection<? extends MultilingualValue>> callback) {
|
||||
this.callback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据当前请求语言回填对象中的多语言字段
|
||||
*
|
||||
* @param body 响应对象
|
||||
*/
|
||||
public void bind(Object body) {
|
||||
if (body == null) {
|
||||
return;
|
||||
}
|
||||
LinkedHashSet<String> langIdSet = new LinkedHashSet<>();
|
||||
// 第一遍只收集多语言 ID,避免递归回填时重复查询
|
||||
collectLangId(body, new IdentityHashMap<>(), langIdSet);
|
||||
if (langIdSet.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Map<String, MultilingualValue> multilingualMap = new LinkedHashMap<>();
|
||||
for (MultilingualValue item : callback.handler(langIdSet)) {
|
||||
multilingualMap.put(item.getId(), item);
|
||||
}
|
||||
// 第二遍执行字段回填,模板替换也在这一遍统一完成
|
||||
fillValue(body, new IdentityHashMap<>(), multilingualMap, TimiSpring.getLanguage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归扫描响应对象,提取所有待翻译字段依赖的多语言 ID
|
||||
*
|
||||
* @param current 当前对象
|
||||
* @param visited 已访问对象,避免循环引用死递归
|
||||
* @param langIdSet 收集到的多语言 ID
|
||||
*/
|
||||
private void collectLangId(Object current, IdentityHashMap<Object, Boolean> visited, LinkedHashSet<String> langIdSet) {
|
||||
switch (current) {
|
||||
case null -> {
|
||||
return;
|
||||
}
|
||||
case Collection<?> collection -> {
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
for (Object item : collection) {
|
||||
collectLangId(item, visited, langIdSet);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case Map<?, ?> map -> {
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
for (Object item : map.values()) {
|
||||
collectLangId(item, visited, langIdSet);
|
||||
}
|
||||
return;
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
if (current.getClass().isArray()) {
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
int length = Array.getLength(current);
|
||||
for (int i = 0; i < length; i++) {
|
||||
collectLangId(Array.get(current, i), visited, langIdSet);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (isSimpleValueType(current.getClass())) {
|
||||
return;
|
||||
}
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
for (BindingField field : getBindingFields(current.getClass())) {
|
||||
String langId = getStringValue(field.langIdField(), current);
|
||||
if (TimiJava.isNotEmpty(langId)) {
|
||||
langIdSet.add(langId);
|
||||
}
|
||||
}
|
||||
for (Field field : getTraverseFields(current.getClass())) {
|
||||
collectLangId(getFieldValue(field, current), visited, langIdSet);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归回填响应对象中的多语言展示字段
|
||||
*
|
||||
* @param current 当前对象
|
||||
* @param visited 已访问对象,避免循环引用死递归
|
||||
* @param multilingualMap 本次响应涉及的多语言缓存
|
||||
* @param language 当前请求语言
|
||||
*/
|
||||
private void fillValue(Object current, IdentityHashMap<Object, Boolean> visited, Map<String, MultilingualValue> multilingualMap, Language.Enum language) {
|
||||
if (current == null) {
|
||||
return;
|
||||
}
|
||||
if (current instanceof Collection<?> collection) {
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
for (Object item : collection) {
|
||||
fillValue(item, visited, multilingualMap, language);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (current instanceof Map<?, ?> map) {
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
for (Object item : map.values()) {
|
||||
fillValue(item, visited, multilingualMap, language);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (current.getClass().isArray()) {
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
int length = Array.getLength(current);
|
||||
for (int i = 0; i < length; i++) {
|
||||
fillValue(Array.get(current, i), visited, multilingualMap, language);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (isSimpleValueType(current.getClass())) {
|
||||
return;
|
||||
}
|
||||
if (visited.put(current, Boolean.TRUE) != null) {
|
||||
return;
|
||||
}
|
||||
for (BindingField field : getBindingFields(current.getClass())) {
|
||||
String langId = getStringValue(field.langIdField(), current);
|
||||
if (TimiJava.isEmpty(langId)) {
|
||||
continue;
|
||||
}
|
||||
MultilingualValue multilingual = multilingualMap.get(langId);
|
||||
if (multilingual == null) {
|
||||
continue;
|
||||
}
|
||||
String value = multilingual.getValue(language);
|
||||
if (TimiJava.isEmpty(value)) {
|
||||
value = multilingual.getValue(Language.Enum.zh_CN);
|
||||
}
|
||||
if (TimiJava.isEmpty(value)) {
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> argMap = getArgMapValue(field.argMapField(), current);
|
||||
if (!argMap.isEmpty()) {
|
||||
value = INTERPOLATOR.inject(value, argMap);
|
||||
}
|
||||
if (TimiJava.isEmpty(value)) {
|
||||
continue;
|
||||
}
|
||||
setFieldValue(field.targetField(), current, value);
|
||||
}
|
||||
for (Field field : getTraverseFields(current.getClass())) {
|
||||
fillValue(getFieldValue(field, current), visited, multilingualMap, language);
|
||||
}
|
||||
}
|
||||
|
||||
private List<BindingField> getBindingFields(Class<?> clazz) {
|
||||
return BINDING_CACHE.computeIfAbsent(clazz, key -> {
|
||||
Map<String, Field> fieldMap = new LinkedHashMap<>();
|
||||
List<Field> declaredFieldList = getAllFields(key);
|
||||
for (Field field : declaredFieldList) {
|
||||
fieldMap.put(field.getName(), field);
|
||||
}
|
||||
List<BindingField> result = new ArrayList<>();
|
||||
for (Field field : declaredFieldList) {
|
||||
MultilingualField annotation = field.getAnnotation(MultilingualField.class);
|
||||
if (annotation == null) {
|
||||
continue;
|
||||
}
|
||||
Field langIdField = fieldMap.get(annotation.value());
|
||||
if (langIdField == null) {
|
||||
log.warn("MultilingualField 配置错误,类 {} 不存在字段 {}", key.getName(), annotation.value());
|
||||
continue;
|
||||
}
|
||||
Field argMapField = null;
|
||||
if (TimiJava.isNotEmpty(annotation.argMap())) {
|
||||
argMapField = fieldMap.get(annotation.argMap());
|
||||
if (argMapField == null) {
|
||||
log.warn("MultilingualField 配置错误,类 {} 不存在字段 {}", key.getName(), annotation.argMap());
|
||||
continue;
|
||||
}
|
||||
if (!Map.class.isAssignableFrom(argMapField.getType())) {
|
||||
log.warn("MultilingualField 配置错误,类 {} 字段 {} 不是 Map", key.getName(), annotation.argMap());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
result.add(new BindingField(field, langIdField, argMapField));
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成需要继续向下遍历的字段列表
|
||||
*
|
||||
* @param clazz 目标类型
|
||||
* @return 可递归字段列表
|
||||
*/
|
||||
private List<Field> getTraverseFields(Class<?> clazz) {
|
||||
return TRAVERSE_CACHE.computeIfAbsent(clazz, key -> {
|
||||
List<Field> result = new ArrayList<>();
|
||||
for (Field field : getAllFields(key)) {
|
||||
if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) {
|
||||
continue;
|
||||
}
|
||||
if (field.getType().isArray() || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())) {
|
||||
field.setAccessible(true);
|
||||
result.add(field);
|
||||
continue;
|
||||
}
|
||||
if (isSimpleValueType(field.getType())) {
|
||||
continue;
|
||||
}
|
||||
field.setAccessible(true);
|
||||
result.add(field);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
private List<Field> getAllFields(Class<?> clazz) {
|
||||
List<Field> result = new ArrayList<>();
|
||||
Class<?> current = clazz;
|
||||
while (current != null && current != Object.class) {
|
||||
for (Field field : current.getDeclaredFields()) {
|
||||
if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) {
|
||||
continue;
|
||||
}
|
||||
field.setAccessible(true);
|
||||
result.add(field);
|
||||
}
|
||||
current = current.getSuperclass();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅接受字符串类型的 langId 字段
|
||||
*
|
||||
* @param field 字段
|
||||
* @param target 对象
|
||||
* @return 多语言 ID
|
||||
*/
|
||||
private String getStringValue(Field field, Object target) {
|
||||
Object value = getFieldValue(field, target);
|
||||
if (value instanceof String string) {
|
||||
return string;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅读取 Map 类型模板参数字段,未配置时返回空 Map
|
||||
*
|
||||
* @param field 字段
|
||||
* @param target 对象
|
||||
* @return 模板参数
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> getArgMapValue(Field field, Object target) {
|
||||
if (field == null) {
|
||||
return Map.of();
|
||||
}
|
||||
Object value = getFieldValue(field, target);
|
||||
if (value instanceof Map<?, ?> map) {
|
||||
return (Map<String, Object>) map;
|
||||
}
|
||||
return Map.of();
|
||||
}
|
||||
|
||||
private Object getFieldValue(Field field, Object target) {
|
||||
try {
|
||||
return field.get(target);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new IllegalStateException("读取字段失败: %s#%s".formatted(target.getClass().getName(), field.getName()), e);
|
||||
}
|
||||
}
|
||||
|
||||
private void setFieldValue(Field field, Object target, Object value) {
|
||||
try {
|
||||
field.set(target, value);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new IllegalStateException("写入字段失败: %s#%s".formatted(target.getClass().getName(), field.getName()), e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isSimpleValueType(Class<?> clazz) {
|
||||
if (clazz.isPrimitive() || clazz.isEnum() || clazz.isAnnotation()) {
|
||||
return true;
|
||||
}
|
||||
if (CharSequence.class.isAssignableFrom(clazz) || Number.class.isAssignableFrom(clazz) || Boolean.class == clazz || Character.class == clazz || UUID.class == clazz || TemporalAccessor.class.isAssignableFrom(clazz) || Class.class == clazz || JsonNode.class.isAssignableFrom(clazz) || File.class.isAssignableFrom(clazz) || Path.class.isAssignableFrom(clazz) || InputStream.class.isAssignableFrom(clazz) || OutputStream.class.isAssignableFrom(clazz) || Reader.class.isAssignableFrom(clazz) || Writer.class.isAssignableFrom(clazz)) {
|
||||
return true;
|
||||
}
|
||||
Package currentPackage = clazz.getPackage();
|
||||
if (currentPackage == null) {
|
||||
return false;
|
||||
}
|
||||
String packageName = currentPackage.getName();
|
||||
return packageName.startsWith("java.") || packageName.startsWith("javax.") || packageName.startsWith("jakarta.") || packageName.startsWith("sun.") || packageName.startsWith("com.fasterxml.jackson.");
|
||||
}
|
||||
|
||||
private record BindingField(Field targetField, Field langIdField, Field argMapField) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.imyeyu.spring.util;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||
|
||||
/**
|
||||
* 统一处理响应中的多语言字段回填
|
||||
*
|
||||
* @author 夜雨
|
||||
* @since 2026-07-17 00:00
|
||||
*/
|
||||
@Component
|
||||
@RestControllerAdvice
|
||||
@RequiredArgsConstructor
|
||||
public class MultilingualResponseBodyAdvice implements ResponseBodyAdvice<Object> {
|
||||
|
||||
private final ObjectProvider<MultilingualFieldBinder> multilingualFieldBinder;
|
||||
|
||||
@Override
|
||||
public boolean supports(@NonNull MethodParameter returnType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object beforeBodyWrite(
|
||||
Object body,
|
||||
@NonNull MethodParameter returnType,
|
||||
@NonNull MediaType selectedContentType,
|
||||
@NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
|
||||
@NonNull ServerHttpRequest request,
|
||||
@NonNull ServerHttpResponse response
|
||||
) {
|
||||
MultilingualFieldBinder binder = multilingualFieldBinder.getIfAvailable();
|
||||
if (binder != null) {
|
||||
binder.bind(body);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.imyeyu.spring.util;
|
||||
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.java.bean.ActionException;
|
||||
import com.imyeyu.spring.bean.Logic;
|
||||
import com.imyeyu.spring.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
@@ -25,7 +25,7 @@ public class RawSQLProvider extends SQLProvider {
|
||||
@Override
|
||||
public String select(ProviderContext context, Object id) {
|
||||
EntityMeta meta = getEntityMeta(context);
|
||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
return "SELECT %s FROM `%s` WHERE `%s` = #{%s}".formatted(meta.selectAllClause, meta.table, meta.idFieldColumn.columnName, id) + " LIMIT 1";
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
package com.imyeyu.spring.util;
|
||||
|
||||
import com.imyeyu.java.TimiJava;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
import com.imyeyu.java.bean.ActionException;
|
||||
import com.imyeyu.spring.config.AbstractRedisConfig;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import org.springframework.data.redis.connection.RedisConnection;
|
||||
import org.springframework.data.redis.core.Cursor;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
@@ -30,12 +29,13 @@ import java.util.function.Consumer;
|
||||
* @author 夜雨
|
||||
* @version 2021-11-21 09:58
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Redis<K, V> {
|
||||
|
||||
@Getter
|
||||
private RedisTemplate<K, V> redis;
|
||||
|
||||
@Getter
|
||||
private RedisSerializer<K> serializer;
|
||||
|
||||
/**
|
||||
@@ -217,7 +217,7 @@ public class Redis<K, V> {
|
||||
* 获取所有值
|
||||
*
|
||||
* @return 所有值
|
||||
* @throws TimiException 异常
|
||||
* @throws ActionException 异常
|
||||
*/
|
||||
public List<V> values() {
|
||||
List<V> r = new ArrayList<>();
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.imyeyu.spring.util;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @author 夜雨
|
||||
* @since 2026-02-25 15:46
|
||||
*/
|
||||
public interface ResponseView {
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @author 夜雨
|
||||
* @since 2026-02-25 15:46
|
||||
*/
|
||||
interface Public {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @author 夜雨
|
||||
* @since 2026-02-25 15:46
|
||||
*/
|
||||
interface Admin extends Public {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ public class SQLProvider extends BaseSQLProvider {
|
||||
*/
|
||||
public String selectByPage(ProviderContext context, @Param("page") Page<?> page) {
|
||||
EntityMeta meta = getEntityMeta(context);
|
||||
return buildSelectByPageSQL(meta, meta.table, page, "#{offset}", "#{limit}");
|
||||
return buildSelectByPageSQL(meta, meta.table, page, "#{offset}", "#{limit}", "");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -42,7 +42,7 @@ public class SQLProvider extends BaseSQLProvider {
|
||||
*/
|
||||
public String countByPage(ProviderContext context, @Param("page") Page<?> page) {
|
||||
EntityMeta meta = getEntityMeta(context);
|
||||
return buildCountByPageSQL(meta, meta.table, page);
|
||||
return buildCountByPageSQL(meta, meta.table, page, "");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user