395 lines
16 KiB
Java
395 lines
16 KiB
Java
package com.example.processor;
|
||
|
||
import com.example.model.AdvancedSearchRequest;
|
||
import com.example.model.PageRequest;
|
||
import com.fasterxml.jackson.core.JsonGenerator;
|
||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||
|
||
import org.apache.camel.Configuration;
|
||
import org.apache.camel.BindToRegistry;
|
||
|
||
import org.apache.camel.Exchange;
|
||
import org.slf4j.Logger;
|
||
import org.slf4j.LoggerFactory;
|
||
|
||
import java.io.IOException;
|
||
import java.text.ParseException;
|
||
import java.text.SimpleDateFormat;
|
||
import java.util.Date;
|
||
import java.util.HashMap;
|
||
import java.util.List;
|
||
import java.util.Map;
|
||
import java.sql.Timestamp;
|
||
|
||
/**
|
||
* 统一请求处理器
|
||
* 适用于Camel Karavan低代码平台配置
|
||
* 通用处理器,不依赖于特定实体类型
|
||
*/
|
||
@Configuration
|
||
@BindToRegistry("requestProcessor")
|
||
public class RequestProcessor {
|
||
private static final Logger LOGGER = LoggerFactory.getLogger(RequestProcessor.class);
|
||
private final ObjectMapper objectMapper;
|
||
|
||
public RequestProcessor() {
|
||
// 配置Jackson序列化
|
||
objectMapper = new ObjectMapper();
|
||
// 启用日期序列化为时间戳
|
||
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
|
||
|
||
// 添加Date序列化器
|
||
SimpleModule module = new SimpleModule();
|
||
module.addSerializer(Date.class, new JsonSerializer<Date>() {
|
||
@Override
|
||
public void serialize(Date value, JsonGenerator gen, SerializerProvider provider)
|
||
throws IOException {
|
||
gen.writeNumber(value.getTime());
|
||
}
|
||
});
|
||
objectMapper.registerModule(module);
|
||
}
|
||
|
||
/**
|
||
* 从请求头中提取ID参数
|
||
*/
|
||
public Long extractId(Exchange exchange) {
|
||
String idStr = exchange.getIn().getHeader("id", String.class);
|
||
return Long.parseLong(idStr);
|
||
}
|
||
|
||
/**
|
||
* 从请求体解析分页参数
|
||
*/
|
||
public Map<String, Object> extractPageCountParams(Exchange exchange) throws Exception {
|
||
Object body = exchange.getIn().getBody();
|
||
PageRequest pageRequest = null;
|
||
if(body instanceof String){
|
||
String bodyStr = (String) body;
|
||
LOGGER.info("分页拿到的请求body: {}", bodyStr);
|
||
pageRequest = objectMapper.readValue(bodyStr, PageRequest.class);
|
||
// 保存请求对象供后续使用
|
||
exchange.setProperty("pageRequest", pageRequest);
|
||
|
||
}else if(body instanceof Map){
|
||
@SuppressWarnings("unchecked")
|
||
Map<String, Object> bodyMap = (Map<String, Object>) body;
|
||
LOGGER.info("分页拿到的请求body: {}", bodyMap);
|
||
pageRequest = objectMapper.convertValue(bodyMap, PageRequest.class);
|
||
}else{
|
||
// 处理其他类型或null
|
||
LOGGER.warn("无法处理的请求体类型: {}", body != null ? body.getClass().getName() : "null");
|
||
pageRequest = new PageRequest();
|
||
pageRequest.setPage(1);
|
||
pageRequest.setSize(10);
|
||
}
|
||
// 保存请求对象供后续使用
|
||
exchange.setProperty("pageRequest", pageRequest);
|
||
|
||
Map<String, Object> params = new HashMap<>();
|
||
params.put("offset", pageRequest.getOffset());
|
||
params.put("limit", pageRequest.getLimit());
|
||
params.put("filters", pageRequest.getFilters());
|
||
params.put("sortField", pageRequest.getSortField());
|
||
params.put("sortOrder", pageRequest.getSortOrder());
|
||
|
||
return params;
|
||
}
|
||
|
||
public Map<String, Object> extractPageParams(Exchange exchange) throws Exception {
|
||
Map<String, Object> params = new HashMap<>();
|
||
PageRequest pageRequest = (PageRequest) exchange.getProperty("pageRequest");
|
||
if(pageRequest == null){
|
||
throw new Exception("分页请求对象为空");
|
||
}
|
||
params.put("offset", pageRequest.getOffset());
|
||
params.put("limit", pageRequest.getLimit());
|
||
params.put("filters", pageRequest.getFilters());
|
||
params.put("sortField", pageRequest.getSortField());
|
||
params.put("sortOrder", pageRequest.getSortOrder());
|
||
return params;
|
||
}
|
||
|
||
/**
|
||
* 从请求体解析高级搜索数量参数
|
||
*/
|
||
public Map<String, Object> extractSearchCountParams(Exchange exchange) throws Exception {
|
||
Object body = exchange.getIn().getBody();
|
||
AdvancedSearchRequest searchRequest = null;
|
||
if(body instanceof String){
|
||
String bodyStr = (String) body;
|
||
LOGGER.info("高级搜索拿到的请求body: {}", bodyStr);
|
||
searchRequest = objectMapper.readValue(bodyStr, AdvancedSearchRequest.class);
|
||
}else if(body instanceof Map){
|
||
@SuppressWarnings("unchecked")
|
||
Map<String, Object> bodyMap = (Map<String, Object>) body;
|
||
LOGGER.info("高级搜索拿到的请求body: {}", bodyMap);
|
||
searchRequest = objectMapper.convertValue(bodyMap, AdvancedSearchRequest.class);
|
||
}else if(body instanceof ObjectMapper){
|
||
searchRequest = objectMapper.convertValue(body, AdvancedSearchRequest.class);
|
||
}else{
|
||
LOGGER.warn("无法处理的请求体类型: {}", body != null ? body.getClass().getName() : "null");
|
||
searchRequest = new AdvancedSearchRequest();
|
||
}
|
||
|
||
// 保存请求对象供后续使用
|
||
exchange.setProperty("searchRequest", searchRequest);
|
||
|
||
// 使用日期序列化为时间戳
|
||
String searchRequestStr = objectMapper.writeValueAsString(searchRequest);
|
||
LOGGER.info("searchRequest转json字符串: {}", searchRequestStr);
|
||
@SuppressWarnings("unchecked")
|
||
Map<String, Object> params = objectMapper.readValue(searchRequestStr, Map.class);
|
||
|
||
LOGGER.info("转换后参数: {}", params);
|
||
return params;
|
||
}
|
||
|
||
/**
|
||
* 从请求体解析高级搜索参数
|
||
*/
|
||
public Map<String, Object> extractSearchParams(Exchange exchange) throws Exception {
|
||
Map<String, Object> params = new HashMap<>();
|
||
AdvancedSearchRequest searchRequest = (AdvancedSearchRequest) exchange.getProperty("searchRequest");
|
||
if(searchRequest == null){
|
||
throw new Exception("高级搜索请求对象为空");
|
||
}
|
||
params.put("offset", searchRequest.getOffset());
|
||
params.put("limit", searchRequest.getLimit());
|
||
params.put("criteria", searchRequest.getCriteria());
|
||
params.put("sortField", searchRequest.getSortField());
|
||
params.put("sortOrder", searchRequest.getSortOrder());
|
||
|
||
return params;
|
||
}
|
||
|
||
/**
|
||
* 准备实体创建参数,通用方法
|
||
* @param <T> 实体类型
|
||
* @param exchange Camel交换对象
|
||
* @param entityClass 实体类Class
|
||
* @return 准备好的实体对象
|
||
*/
|
||
public <T> T prepareEntity(Exchange exchange, Class<T> entityClass) throws Exception {
|
||
String body = exchange.getIn().getBody(String.class);
|
||
T entity = objectMapper.readValue(body, entityClass);
|
||
|
||
// 通过反射设置创建和更新时间(如果实体有这些字段)
|
||
try {
|
||
// 尝试设置创建时间
|
||
try {
|
||
java.lang.reflect.Method setCreatedAt = entity.getClass().getMethod("setCreatedAt", Date.class);
|
||
if (setCreatedAt != null) {
|
||
setCreatedAt.invoke(entity, new Date());
|
||
}
|
||
} catch (NoSuchMethodException e) {
|
||
// 实体没有这个方法,忽略
|
||
}
|
||
|
||
// 尝试设置更新时间
|
||
try {
|
||
java.lang.reflect.Method setUpdatedAt = entity.getClass().getMethod("setUpdatedAt", Date.class);
|
||
if (setUpdatedAt != null) {
|
||
setUpdatedAt.invoke(entity, new Date());
|
||
}
|
||
} catch (NoSuchMethodException e) {
|
||
// 实体没有这个方法,忽略
|
||
}
|
||
|
||
// 尝试设置默认激活状态
|
||
try {
|
||
java.lang.reflect.Method getActive = entity.getClass().getMethod("getActive");
|
||
java.lang.reflect.Method setActive = entity.getClass().getMethod("setActive", Boolean.class);
|
||
|
||
if (getActive != null && setActive != null) {
|
||
Boolean active = (Boolean) getActive.invoke(entity);
|
||
if (active == null) {
|
||
setActive.invoke(entity, true);
|
||
}
|
||
}
|
||
} catch (NoSuchMethodException e) {
|
||
// 实体没有这些方法,忽略
|
||
}
|
||
} catch (Exception e) {
|
||
LOGGER.warn("设置实体属性时出错", e);
|
||
}
|
||
|
||
return entity;
|
||
}
|
||
|
||
/**
|
||
* 准备实体更新参数,通用方法
|
||
* @param <T> 实体类型
|
||
* @param exchange Camel交换对象
|
||
* @param entityClass 实体类Class
|
||
* @return 准备好的实体对象
|
||
*/
|
||
public <T> T prepareEntityWithId(Exchange exchange, Class<T> entityClass) throws Exception {
|
||
String idStr = exchange.getIn().getHeader("id", String.class);
|
||
Long id = Long.parseLong(idStr);
|
||
|
||
String body = exchange.getIn().getBody(String.class);
|
||
T entity = objectMapper.readValue(body, entityClass);
|
||
|
||
// 通过反射设置ID和更新时间
|
||
try {
|
||
// 设置ID
|
||
try {
|
||
java.lang.reflect.Method setId = entity.getClass().getMethod("setId", Long.class);
|
||
if (setId != null) {
|
||
setId.invoke(entity, id);
|
||
}
|
||
} catch (NoSuchMethodException e) {
|
||
LOGGER.warn("实体类 {} 没有 setId 方法", entityClass.getName());
|
||
}
|
||
|
||
// 设置更新时间
|
||
try {
|
||
java.lang.reflect.Method setUpdatedAt = entity.getClass().getMethod("setUpdatedAt", Date.class);
|
||
if (setUpdatedAt != null) {
|
||
setUpdatedAt.invoke(entity, new Date());
|
||
}
|
||
} catch (NoSuchMethodException e) {
|
||
// 实体没有这个方法,忽略
|
||
}
|
||
} catch (Exception e) {
|
||
LOGGER.warn("设置实体属性时出错", e);
|
||
}
|
||
|
||
return entity;
|
||
}
|
||
|
||
/**
|
||
* 创建实体不存在的错误响应
|
||
*/
|
||
public Map<String, String> createNotFoundResponse() {
|
||
Map<String, String> response = new HashMap<>();
|
||
response.put("error", "记录不存在");
|
||
return response;
|
||
}
|
||
|
||
/**
|
||
* 创建不存在的错误响应(指定实体名称)
|
||
*/
|
||
public Map<String, String> createNotFoundResponse(String entityName) {
|
||
Map<String, String> response = new HashMap<>();
|
||
response.put("error", entityName + "不存在");
|
||
return response;
|
||
}
|
||
|
||
/**
|
||
* 创建冲突的错误响应
|
||
*/
|
||
public Map<String, String> createConflictResponse(String field) {
|
||
Map<String, String> response = new HashMap<>();
|
||
response.put("error", field + "已存在");
|
||
return response;
|
||
}
|
||
|
||
/**
|
||
* 设置HTTP状态码
|
||
*/
|
||
public void setStatusCode(Exchange exchange, int code) {
|
||
exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, code);
|
||
}
|
||
|
||
public Map<String, Object> convertJsonWithDates(String json) throws Exception {
|
||
// 将JSON字符串转为Map
|
||
ObjectMapper mapper = new ObjectMapper();
|
||
Map<String, Object> map = mapper.readValue(json, Map.class);
|
||
|
||
// 递归处理日期字段
|
||
processDateFields(map);
|
||
|
||
return map;
|
||
}
|
||
|
||
@SuppressWarnings("unchecked")
|
||
private void processDateFields(Object obj) throws ParseException {
|
||
if (obj instanceof Map) {
|
||
Map<String, Object> map = (Map<String, Object>) obj;
|
||
|
||
// 处理Map中的每个键值对
|
||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||
String key = entry.getKey();
|
||
Object value = entry.getValue();
|
||
|
||
if (value instanceof String && isDateString((String) value)) {
|
||
// 如果是日期字符串,则转换为时间戳
|
||
map.put(key, parseTimestamp((String) value));
|
||
} else if (value instanceof List) {
|
||
// 处理数组
|
||
processList((List<Object>) value);
|
||
} else if (value instanceof Map) {
|
||
// 递归处理子Map
|
||
processDateFields(value);
|
||
}
|
||
}
|
||
|
||
// 特殊处理criteria字段
|
||
if (map.containsKey("criteria") && map.get("criteria") instanceof List) {
|
||
processList((List<Object>) map.get("criteria"));
|
||
}
|
||
}
|
||
}
|
||
|
||
@SuppressWarnings("unchecked")
|
||
private void processList(List<Object> list) throws ParseException {
|
||
for (int i = 0; i < list.size(); i++) {
|
||
Object item = list.get(i);
|
||
|
||
if (item instanceof String && isDateString((String) item)) {
|
||
// 如果是日期字符串,则转换为时间戳
|
||
list.set(i, parseTimestamp((String) item));
|
||
} else if (item instanceof Map) {
|
||
Map<String, Object> mapItem = (Map<String, Object>) item;
|
||
processDateFields(mapItem);
|
||
|
||
// 特殊处理value为数组的情况(如BETWEEN操作符)
|
||
if (mapItem.containsKey("value") && mapItem.get("value") instanceof List) {
|
||
processList((List<Object>) mapItem.get("value"));
|
||
}
|
||
|
||
// 处理subCriteria
|
||
if (mapItem.containsKey("subCriteria") && mapItem.get("subCriteria") instanceof List) {
|
||
processList((List<Object>) mapItem.get("subCriteria"));
|
||
}
|
||
} else if (item instanceof List) {
|
||
// 递归处理子List
|
||
processList((List<Object>) item);
|
||
}
|
||
}
|
||
}
|
||
|
||
// private boolean isDateString(String str) {
|
||
// // 检查字符串是否符合ISO日期格式 "yyyy-MM-dd'T'HH:mm:ss"
|
||
// return str.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}");
|
||
// }
|
||
private boolean isDateString(String str) {
|
||
// 修改正则表达式匹配更多日期格式(包括带毫秒和时区的格式)
|
||
return str.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:?\\d{2})?");
|
||
}
|
||
|
||
// private long parseTimestamp(String dateStr) throws ParseException {
|
||
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
|
||
// return sdf.parse(dateStr).getTime();
|
||
// }
|
||
// private Timestamp parseTimestamp(String dateStr) throws ParseException {
|
||
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
|
||
// return new Timestamp(sdf.parse(dateStr).getTime());
|
||
// }
|
||
private Timestamp parseTimestamp(String dateStr) throws ParseException {
|
||
try {
|
||
// 尝试直接解析ISO格式(带时区)
|
||
return Timestamp.valueOf(dateStr.replace('T', ' ').substring(0, 19));
|
||
} catch (Exception e) {
|
||
// 回退到使用SimpleDateFormat
|
||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
|
||
return new Timestamp(sdf.parse(dateStr).getTime());
|
||
}
|
||
}
|
||
} |