7 Commits
Author SHA1 Message Date
timi 42dee2e4ad Merge pull request 'v0.0.7' (#7) from dev into master
Reviewed-on: #7
2026-03-27 15:10:56 +00:00
timi 66eb6108cd Merge pull request 'v0.0.6' (#6) from dev into master
Reviewed-on: #6
2026-03-21 10:16:59 +00:00
timi 82f950e71d Merge pull request 'v0.0.5' (#5) from dev into master
Reviewed-on: #5
2026-03-17 03:24:06 +00:00
timi cceabb0c8d Merge pull request 'v0.0.5' (#4) from dev into master
Reviewed-on: #4
2026-03-17 03:07:34 +00:00
timi 62de8e4885 Merge pull request 'v0.0.4' (#3) from dev into master
Reviewed-on: #3
2026-03-16 09:18:09 +00:00
timi 9f7460e959 Merge pull request 'v0.0.3' (#2) from dev into master
Reviewed-on: #2
2026-02-10 10:56:12 +00:00
timi 90d4c5e5f6 Merge pull request 'v0.0.2' (#1) from dev into master
Reviewed-on: #1
2026-01-19 09:53:14 +00:00
30 changed files with 195 additions and 1203 deletions
-2
View File
@@ -1,2 +0,0 @@
/cache
/project.local.yml
-154
View File
@@ -1,154 +0,0 @@
# 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: []
+8 -8
View File
@@ -7,19 +7,19 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.13</version>
<version>3.5.11</version>
<relativePath/>
</parent>
<groupId>com.imyeyu.spring</groupId>
<artifactId>timi-spring</artifactId>
<version>0.1.0</version>
<version>0.0.7</version>
<packaging>jar</packaging>
<properties>
<java.version>21</java.version>
<maven.test.skip>true</maven.test.skip>
<springboot.version>3.5.13</springboot.version>
<springboot.version>3.5.11</springboot.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@@ -131,17 +131,17 @@
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.5</version>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.13.1</version>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>com.imyeyu.lang</groupId>
<artifactId>timi-lang</artifactId>
<version>0.1.0</version>
<groupId>com.imyeyu.io</groupId>
<artifactId>timi-io</artifactId>
<version>0.0.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
+17 -69
View File
@@ -2,10 +2,10 @@ package com.imyeyu.spring;
import com.imyeyu.io.IO;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.ResultCode;
import com.imyeyu.java.bean.Language;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
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 ActionException 请求异常
* @throws TimiException 请求异常
*/
public static ServletRequestAttributes getServletRequestAttributes() {
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes sra) {
return sra;
}
throw new ActionException(ResultCode.ERROR_NPE_VARIABLE);
throw new TimiException(TimiCode.ERROR_NPE_VARIABLE);
}
/**
@@ -109,7 +109,7 @@ public class TimiSpring {
*/
public static String cutURIStartAt(String flag) {
int indexOf = getURI().indexOf(flag);
ActionException.requiredTrue(-1 < indexOf, "not found flag: %s".formatted(flag));
TimiException.requiredTrue(-1 < indexOf, "not found flag: %s".formatted(flag));
return getURI().substring(indexOf + flag.length());
}
@@ -346,16 +346,7 @@ public class TimiSpring {
* @return 令牌
*/
public static String getToken() {
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"));
return TimiJava.firstNotEmpty(getHeader("Token"), getHeader("token"), getRequestArg("token"), getRequestArg("Token"));
}
/**
@@ -399,7 +390,7 @@ public class TimiSpring {
* 获取请求 IP
*
* @return 请求 IP
* @throws ActionException 服务异常
* @throws TimiException 服务异常
*/
public static String getRequestIP() {
String ip = getHeader("x-forwarded-for");
@@ -436,57 +427,17 @@ public class TimiSpring {
*/
public static RequestRange getRequestRange(long total) throws IOException {
HttpServletResponse resp = getResponse();
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);
String range = getRequestAttrAsString("Range");
if (range == null || !range.startsWith("bytes=")) {
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);
@@ -512,9 +463,6 @@ 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);
@@ -1,31 +0,0 @@
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 "";
}
@@ -1,43 +0,0 @@
package com.imyeyu.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 读取 JSON 请求体中的单个字段并绑定到接口参数。
*
* <p>默认使用方法参数名作为 JSON 字段名,也可以手动指定字段名。
*
* <pre>
* public void run(@RequestBodyValue String data) {
* }
*
* public void run(@RequestBodyValue("value") Long id) {
* }
* </pre>
*
* @author 夜雨
* @version 2026-04-08 11:00
*/
@Documented
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestBodyValue {
/**
* JSON 字段名,为空时使用方法参数名。
*
* @return JSON 字段名
*/
String value() default "";
/**
* 是否必须存在该字段。
*
* @return true 表示必须存在
*/
boolean required() default true;
}
@@ -1,82 +0,0 @@
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.ResultCode;
import com.imyeyu.java.bean.ActionException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* {@link RequestBodyValue} 参数解析器。
*
* @author 夜雨
* @version 2026-04-08 11:00
*/
@Component
public class RequestBodyValueArgumentResolver implements HandlerMethodArgumentResolver {
private static final String REQUEST_BODY_JSON_NODE_ATTR = RequestBodyValueArgumentResolver.class.getName() + ".REQUEST_BODY_JSON_NODE";
private final ObjectMapper objectMapper;
/**
* 创建 {@link RequestBodyValue} 参数解析器。
*
* @param objectMapper Jackson 对象映射器
*/
public RequestBodyValueArgumentResolver(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public boolean supportsParameter(@NonNull MethodParameter parameter) {
return parameter.hasParameterAnnotation(RequestBodyValue.class);
}
@Override
public Object resolveArgument(@NonNull MethodParameter parameter, ModelAndViewContainer mavContainer, @NonNull NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
RequestBodyValue bodyValue = parameter.getParameterAnnotation(RequestBodyValue.class);
if (bodyValue == null) {
return null;
}
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
ActionException.required(request, "not found request");
assert request != null;
JsonNode requestBody;
{
Object cached = request.getAttribute(REQUEST_BODY_JSON_NODE_ATTR);
if (cached instanceof JsonNode jsonNode) {
return jsonNode;
}
byte[] bodyBytes = request.getInputStream().readAllBytes();
ActionException.requiredTrue(1 < bodyBytes.length, "empty request body");
requestBody = objectMapper.readTree(bodyBytes);
ActionException.requiredTrue(requestBody != null && requestBody.isObject(), "not object request body");
request.setAttribute(REQUEST_BODY_JSON_NODE_ATTR, requestBody);
}
String fieldName = bodyValue.value();
{
if (TimiJava.isEmpty(fieldName)) {
fieldName = parameter.getParameterName();
}
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 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 #inSeconds()} 生命周期内(秒)限制访问 {@link #value()} 次
* <p>{@link #lifeCycle()} 生命周期内(秒)限制访问 {@link #value()} 次
*
* @author 夜雨
* @version 2021-08-16 17:57
@@ -32,5 +32,5 @@ public @interface RequestRateLimit {
*
* @return 生命周期秒数
*/
int inSeconds() default 10;
int lifeCycle() default 10;
}
@@ -45,7 +45,7 @@ public abstract class RequestRateLimitAbstractInterceptor implements HandlerInte
return true;
}
// 频率限制
return beforeRun(req, resp, buildId(handlerMethod), requestRateLimit.inSeconds(), requestRateLimit.value());
return beforeRun(req, resp, buildId(handlerMethod), requestRateLimit.lifeCycle(), requestRateLimit.value());
}
return true;
}
@@ -37,6 +37,34 @@ 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,8 +1,6 @@
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;
@@ -18,19 +16,15 @@ 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,8 +1,6 @@
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;
@@ -18,6 +16,5 @@ public class Entity extends BaseEntity implements IDEntity<Long> {
/** ID */
@Id
@JsonView(ResponseView.Public.class)
protected Long id;
}
@@ -1,11 +1,9 @@
package com.imyeyu.spring.entity;
import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.lang.bean.Language;
import com.imyeyu.lang.bean.MultilingualValue;
import com.imyeyu.java.bean.Language;
import com.imyeyu.java.ref.Ref;
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;
@@ -17,27 +15,33 @@ import lombok.EqualsAndHashCode;
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class Multilingual extends Language implements MultilingualValue, IDEntity<String>, Creatable, Updatable, Deletable, Destroyable {
public class Multilingual extends Language implements 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,9 +1,7 @@
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;
@@ -20,6 +18,5 @@ 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.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
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();
}
ActionException.required(baseMapper, "mapper() can not be null");
TimiException.required(baseMapper, "mapper() can not be null");
}
@Override
@@ -1,6 +1,6 @@
package com.imyeyu.spring.service;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
/**
* 可创建实体服务
@@ -15,7 +15,7 @@ public interface CreatableService<T> {
* 创建数据
*
* @param t 数据对象
* @throws ActionException 服务异常
* @throws TimiException 服务异常
*/
void create(T t);
}
@@ -1,6 +1,6 @@
package com.imyeyu.spring.service;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
/**
* 可软删除实体服务
@@ -15,7 +15,7 @@ public interface DeletableService<P> {
* 软删除
*
* @param p 数据对象
* @throws ActionException 服务异常
* @throws TimiException 服务异常
*/
void delete(P p);
}
@@ -1,6 +1,6 @@
package com.imyeyu.spring.service;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
/**
* 可销毁(物理删除)实体服务
@@ -15,7 +15,7 @@ public interface DestroyableService<P> {
* 销毁(物理删除)
*
* @param p 数据对象
* @throws ActionException 服务异常
* @throws TimiException 服务异常
*/
void destroy(P p);
}
@@ -1,6 +1,6 @@
package com.imyeyu.spring.service;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
/**
* 可更新实体服务
@@ -15,7 +15,7 @@ public interface UpdatableService<T> {
* 修改数据
*
* @param t 数据对象
* @throws ActionException 服务异常
* @throws TimiException 服务异常
*/
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.ResultCode;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.java.ref.Ref;
import com.imyeyu.spring.annotation.table.AutoUUID;
import com.imyeyu.spring.annotation.table.Column;
@@ -31,7 +31,6 @@ 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;
@@ -82,21 +81,6 @@ 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));
@@ -104,11 +88,7 @@ public abstract class BaseSQLProvider {
appendSoftDeleteCondition(sql, meta);
// 添加 Page 查询条件
if (pageParameterPath.isEmpty()) {
appendPageConditions(sql, page);
} else {
appendPageConditions(sql, page, pageParameterPath);
}
appendPageConditions(sql, page);
// 添加排序
appendOrderBy(sql, meta, page);
@@ -127,19 +107,6 @@ 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));
@@ -147,11 +114,7 @@ public abstract class BaseSQLProvider {
appendSoftDeleteCondition(sql, meta);
// 添加 Page 查询条件
if (pageParameterPath.isEmpty()) {
appendPageConditions(sql, page);
} else {
appendPageConditions(sql, page, pageParameterPath);
}
appendPageConditions(sql, page);
return sql.toString();
}
@@ -175,82 +138,30 @@ 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) {
// 精准查询
appendPageExampleConditions(
sql,
page.getEqualsExample(),
page.getEqualsLogic(),
false,
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.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;
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(')');
}
}
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);
}
/**
@@ -320,7 +231,7 @@ public abstract class BaseSQLProvider {
Ref.setFieldValue(entity, fc.field, uuid);
}
} catch (IllegalAccessException e) {
throw new ActionException(ResultCode.ERROR, "auto set field:%s value error".formatted(fc.fieldName));
throw new TimiException(TimiCode.ERROR).msgKey("auto set field:%s value error".formatted(fc.fieldName));
}
if (entity instanceof Creatable creatableEntity && creatableEntity.getCreatedAt() == null) {
creatableEntity.setCreatedAt(Time.now());
@@ -339,7 +250,7 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildSelectByIdSQL(EntityMeta meta, String tableName, String idParam) {
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
TimiException.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(
@@ -388,8 +299,8 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildUpdateSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix) {
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));
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));
if (entity instanceof Updatable updatable) {
updatable.setUpdatedAt(Time.now());
@@ -417,8 +328,8 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildUpdateSelectiveSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix) {
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));
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));
if (entity instanceof Updatable updatable) {
updatable.setUpdatedAt(Time.now());
@@ -446,8 +357,8 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildDeleteSQL(EntityMeta meta, String tableName, String idParam) {
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));
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));
return "UPDATE `%s` SET `deleted_at` = %s WHERE `%s` = #{%s}".formatted(
tableName,
@@ -468,13 +379,13 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildDeleteAllByExampleSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix, Logic logic) {
ActionException.required(meta.canDelete, "not allow delete for %s".formatted(meta.entityClass));
TimiException.required(meta.canDelete, "not allow delete for %s".formatted(meta.entityClass));
FieldColumn deleteColumn = meta.getFieldColumnList().stream()
.filter(fc -> fc.isDeleteColumn)
.findFirst()
.orElse(null);
ActionException.required(deleteColumn, "unknown delete column, use com.imyeyu.spring.annotation.table.DeleteColumn annotation on field");
TimiException.required(deleteColumn, "unknown delete column, use com.imyeyu.spring.annotation.table.DeleteColumn annotation on field");
assert deleteColumn != null;
assert deleteColumn.deleteColumnType != null;
@@ -501,8 +412,8 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildDestroySQL(EntityMeta meta, String tableName, String idParam) {
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));
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));
return "DELETE FROM `%s` WHERE `%s` = #{%s}".formatted(tableName, meta.idFieldColumn.columnName, idParam);
}
@@ -518,7 +429,7 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildDestroyAllByExampleSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix, Logic logic) {
ActionException.required(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
TimiException.required(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
String destroyClause = meta.fieldColumnList.stream()
.filter(FieldColumn::isNotId)
.filter(fc -> fc.isNotEmpty(entity))
@@ -583,7 +494,7 @@ public abstract class BaseSQLProvider {
this.table = Text.camelCase2underscore(entityClass.getSimpleName());
} else {
this.table = table.value();
ActionException.required(this.table, String.format("empty table annotation value for %s entity", entityClass.getName()));
TimiException.required(this.table, String.format("empty table annotation value for %s entity", entityClass.getName()));
}
List<Field> allFieldList = Ref.listAllFields(entityClass);
FieldColumn idFieldColumn = null;
@@ -595,7 +506,7 @@ public abstract class BaseSQLProvider {
}
FieldColumn fieldColumn = new FieldColumn(field);
if (fieldColumn.isId) {
ActionException.requiredNull(idFieldColumn, String.format("multi id field for %s entity", entityClass.getName()));
TimiException.requiredNull(idFieldColumn, String.format("multi id field for %s entity", entityClass.getName()));
idFieldColumn = fieldColumn;
}
fieldColumnList.add(fieldColumn);
@@ -713,7 +624,7 @@ public abstract class BaseSQLProvider {
columnName = Text.camelCase2underscore(field.getName());
} else {
columnName = column.value();
ActionException.required(columnName, "empty field:%s column annotation value for %s entity".formatted(field.getName(), field.getDeclaringClass()));
TimiException.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);
@@ -737,7 +648,11 @@ public abstract class BaseSQLProvider {
* @return true 为 null
*/
public boolean isNull(Object entity) {
return getValue(entity) == null;
try {
return Ref.getFieldValue(entity, field, Object.class) == null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**
@@ -757,7 +672,11 @@ public abstract class BaseSQLProvider {
* @return true 为空
*/
public boolean isEmpty(Object entity) {
return TimiJava.isEmpty(getValue(entity));
try {
return TimiJava.isEmpty(Ref.getFieldValue(entity, field, Object.class));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**
@@ -777,18 +696,8 @@ public abstract class BaseSQLProvider {
* @return 字符串值
*/
public String getAsString(Object obj) {
return getValue(obj).toString();
}
/**
* 获取字段值
*
* @param entity 实体
* @return 字段值
*/
public Object getValue(Object entity) {
try {
return Ref.getFieldValue(entity, field, Object.class);
return field.get(obj).toString();
} 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}", "page.");
return buildSelectByPageSQL(meta, tableName, page, "#{page.offset}", "#{page.limit}");
}
/**
@@ -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, "page.");
return buildCountByPageSQL(meta, tableName, page);
}
/**
@@ -1,20 +1,13 @@
package com.imyeyu.spring.util;
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 com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.java.bean.timi.TimiResponse;
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;
@@ -34,15 +27,10 @@ public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
private final ObjectProvider<MultilingualResolver> multilingualResolverProvider;
/**
* 创建全局异常处理器
*
* @param multilingualResolverProvider 消息解析器提供器
*/
public GlobalExceptionHandler(ObjectProvider<MultilingualResolver> multilingualResolverProvider) {
this.multilingualResolverProvider = multilingualResolverProvider;
public GlobalExceptionHandler() {
}
@Value("${spring.profiles.active}")
@@ -54,17 +42,13 @@ public class GlobalExceptionHandler {
* @param e 异常
* @return 异常返回
*/
@IgnoreGlobalReturn
@ExceptionHandler(HttpMessageConversionException.class)
public Object conversionException(HttpMessageConversionException e) {
public TimiResponse<?> conversionException(HttpMessageConversionException e) {
log.warn(e.getMessage());
if (env.contains("dev") || log.isDebugEnabled()) {
log.error("conversion error", e);
}
if (ignoreCommittedBinaryResponse()) {
return null;
}
return fail(ResultCode.ARG_BAD, "invalid.body");
return new TimiResponse<>(TimiCode.ARG_BAD).msgKey("invalid.body");
}
/**
@@ -73,17 +57,13 @@ public class GlobalExceptionHandler {
* @param e 异常
* @return 异常返回
*/
@IgnoreGlobalReturn
@ExceptionHandler(ServletException.class)
public Object headerException(ServletException e) {
public TimiResponse<?> headerException(ServletException e) {
log.warn(e.getMessage());
if (env.contains("dev") || log.isDebugEnabled()) {
log.error("header error", e);
}
if (ignoreCommittedBinaryResponse()) {
return null;
}
return fail(ResultCode.REQUEST_BAD, "invalid.request");
return new TimiResponse<>(TimiCode.REQUEST_BAD).msgKey("invalid.request");
}
/**
@@ -92,20 +72,19 @@ public class GlobalExceptionHandler {
* @param e 异常
* @return 异常返回
*/
@IgnoreGlobalReturn
@ExceptionHandler({BindException.class, ValidationException.class, MethodArgumentNotValidException.class, TypeMismatchException.class})
public Response<?> paramsException(Exception e) {
public TimiResponse<?> paramsException(Exception e) {
if (e instanceof MethodArgumentNotValidException subE) {
log.warn("request error", e);
FieldError error = subE.getBindingResult().getFieldError();
if (error != null) {
return fail(ResultCode.ARG_BAD, "[%s] %s".formatted(error.getField(), error.getDefaultMessage()));
return new TimiResponse<>(TimiCode.ARG_BAD, "[%s] %s".formatted(error.getField(), error.getDefaultMessage()));
}
}
if (env.startsWith("dev") || log.isDebugEnabled()) {
log.error("request error", e);
}
return fail(ResultCode.REQUEST_BAD, "invalid.arg");
return new TimiResponse<>(TimiCode.REQUEST_BAD).msgKey("invalid.arg");
}
/**
@@ -114,112 +93,17 @@ public class GlobalExceptionHandler {
* @param e 异常
* @return 异常返回
*/
@IgnoreGlobalReturn
@ExceptionHandler(Throwable.class)
public Object error(Throwable e) {
if (e instanceof ActionException timiE) {
public TimiResponse<?> error(Throwable e) {
if (e instanceof TimiException timiE) {
if (!env.startsWith("prod") || log.isDebugEnabled()) {
log.error(timiE.getMessage(), e);
}
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());
// 一般异常
return timiE.toResponse();
}
// 致命异常
log.error("fatal error", e);
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/");
return new TimiResponse<>(TimiCode.ERROR).msgKey("service.error");
}
}
@@ -1,18 +1,19 @@
package com.imyeyu.spring.util;
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.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.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;
@@ -22,24 +23,24 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.util.Objects;
/**
* 全局返回处理器,包装 Response
* 全局返回处理器,包装 TimiResponse
*
* @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 final ObjectMapper objectMapper;
/** 多语言头处理回调 */
private CallbackArgReturn<LanguageMsgMapping<?>, String> multilingualHeader;
/**
* 创建全局返回处理器
*
* @param objectMapper JSON 对象映射器
*/
public GlobalReturnHandler(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
public GlobalReturnHandler() {
}
@Override
@@ -54,24 +55,27 @@ public class GlobalReturnHandler implements ResponseBodyAdvice<Object> {
@NonNull MediaType selectedContentType,
@NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
@NonNull ServerHttpRequest request,
@NonNull ServerHttpResponse response
) {
Response<?> result;
if (body instanceof Response<?> Response) {
result = Response;
@NonNull ServerHttpResponse response)
{
TimiResponse<?> result;
if (body instanceof TimiResponse<?> timiResponse) {
// 可能已被全局异常包装
result = timiResponse;
} else {
result = new Response<>(ResultCode.SUCCESS, body);
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());
}
if (30000 < result.getCode()) {
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);
}
log.warn("ID: {} Response -> Exception.{}.{}", TimiSpring.getSessionAttr(AOPLogInterceptor.REQUEST_ID), result.getCode(), result.getMsg());
}
return result;
}
@@ -1,364 +0,0 @@
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) {
}
}
@@ -1,48 +0,0 @@
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.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
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);
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
TimiException.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,10 +1,8 @@
package com.imyeyu.spring.util;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.config.AbstractRedisConfig;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
@@ -29,14 +27,7 @@ import java.util.function.Consumer;
* @author 夜雨
* @version 2021-11-21 09:58
*/
@AllArgsConstructor
public class Redis<K, V> {
@Getter
private RedisTemplate<K, V> redis;
@Getter
private RedisSerializer<K> serializer;
public record Redis<K, V>(RedisTemplate<K, V> redis, RedisSerializer<K> serializer) {
/**
* 加锁
@@ -217,7 +208,7 @@ public class Redis<K, V> {
* 获取所有值
*
* @return 所有值
* @throws ActionException 异常
* @throws TimiException 异常
*/
public List<V> values() {
List<V> r = new ArrayList<>();
@@ -87,29 +87,19 @@ public class RedisSerializers {
/**
* Json 序列化
*
* @param <T> 数据类型
* @param <T> 数据类型
* @param clazz 数据类型
* @return Redis 序列化器
*/
public static <T> RedisSerializer<T> jacksonSerializer(Class<T> clazz) {
return jacksonSerializer(new ObjectMapper(), clazz);
}
/**
* Json 序列化
*
* @param <T> 数据类型
* @param mapper 序列化对象
* @param clazz 数据类型
* @return Redis 序列化器
*/
public static <T> RedisSerializer<T> jacksonSerializer(ObjectMapper mapper, Class<T> clazz) {
return new RedisSerializer<>() {
private static final ObjectMapper JACKSON = new ObjectMapper();
@Override
public byte[] serialize(T object) throws SerializationException {
try {
return mapper.writeValueAsString(object).getBytes(StandardCharsets.UTF_8);
return JACKSON.writeValueAsString(object).getBytes(StandardCharsets.UTF_8);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
@@ -121,7 +111,7 @@ public class RedisSerializers {
return null;
}
try {
return mapper.readValue(new String(bytes, StandardCharsets.UTF_8), clazz);
return JACKSON.readValue(new String(bytes, StandardCharsets.UTF_8), clazz);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -1,30 +0,0 @@
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);
}
/**