From cb7f9f66a9af65ce787173048fb45c2ec03cf4ab Mon Sep 17 00:00:00 2001 From: maojian <550076202@qq.com> Date: Wed, 7 Jan 2026 19:29:28 +0800 Subject: [PATCH] =?UTF-8?q?api=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/com/bw/ocr/entity/AppResultDoc.java | 18 +- .../src/main/java/com/bw/ocr/entity/Constants.java | 1 + .../bw/ocr/service/impl/OcrTaskServiceImpl.java | 130 ++------ .../com/bw/opai/app/controller/AppController.java | 17 +- .../src/main/java/com/bw/opai/app/dto/App.java | 27 +- .../src/main/java/com/bw/opai/app/dto/Task.java | 72 +++++ .../java/com/bw/opai/app/entity/AppResultDoc.java | 25 +- .../java/com/bw/opai/app/mapper/TaskMapper.java | 18 ++ .../java/com/bw/opai/app/service/AppService.java | 5 +- .../bw/opai/app/service/impl/AppServiceImpl.java | 358 +++++++++++---------- .../src/main/java/com/bw/opai/utils/Constants.java | 5 + 11 files changed, 377 insertions(+), 299 deletions(-) create mode 100644 opai-api/src/main/java/com/bw/opai/app/dto/Task.java create mode 100644 opai-api/src/main/java/com/bw/opai/app/mapper/TaskMapper.java diff --git a/ocr-service/src/main/java/com/bw/ocr/entity/AppResultDoc.java b/ocr-service/src/main/java/com/bw/ocr/entity/AppResultDoc.java index b5236dd..7ae3fe0 100644 --- a/ocr-service/src/main/java/com/bw/ocr/entity/AppResultDoc.java +++ b/ocr-service/src/main/java/com/bw/ocr/entity/AppResultDoc.java @@ -4,6 +4,7 @@ package com.bw.ocr.entity; import java.io.Serializable; import java.util.Map; + import lombok.Data; /** @@ -17,15 +18,22 @@ public class AppResultDoc implements Serializable { private static final long serialVersionUID = 1L; - /** 完成时间(毫秒时间戳) */ - private Long finishTime; + /** 任务ID */ + private String taskId; - /** 执行状态 */ + /** 应用id */ + private String appId; + + /** 状态 0 进行中,1成功,2失败 */ private Integer status; + /** 创建时间(毫秒时间戳) */ + private Long createTime; + /** 执行结果(可索引) */ private Map result; - /** 最后修改时间(毫秒时间戳) */ - private Long lastEdit; + /** 逻辑删除标识:0-未删除 1-已删除 */ + private Integer del; + } diff --git a/ocr-service/src/main/java/com/bw/ocr/entity/Constants.java b/ocr-service/src/main/java/com/bw/ocr/entity/Constants.java index c1f6366..7059076 100644 --- a/ocr-service/src/main/java/com/bw/ocr/entity/Constants.java +++ b/ocr-service/src/main/java/com/bw/ocr/entity/Constants.java @@ -20,6 +20,7 @@ public class Constants { public static final String MESSAGE = "message"; /******************************api使用*******************************/ public static final String CONTENT = "content"; + public static final String ERROR = "error"; public static final String WROD_COUNT = "wordCount"; public static final String TRACE = "trace"; public static final String PARSE_FIAL = "解析失败"; diff --git a/ocr-service/src/main/java/com/bw/ocr/service/impl/OcrTaskServiceImpl.java b/ocr-service/src/main/java/com/bw/ocr/service/impl/OcrTaskServiceImpl.java index 84769a1..bde3f35 100644 --- a/ocr-service/src/main/java/com/bw/ocr/service/impl/OcrTaskServiceImpl.java +++ b/ocr-service/src/main/java/com/bw/ocr/service/impl/OcrTaskServiceImpl.java @@ -65,24 +65,9 @@ public class OcrTaskServiceImpl implements OcrTaskService { @Value("${api.query-url}") private String queryUrl; - @Value("${elasticsearch.url}") - private String esUrl; + @Value("${api.save-url}") + private String saveUrl; - @Value("${elasticsearch.username}") - private String esUser; - - @Value("${elasticsearch.password}") - private String esPassword; - - @Value("${elasticsearch.index-name}") - private String indexName; - - private final ObjectMapper objectMapper; - - @Autowired - public OcrTaskServiceImpl(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } @Override public void create(Map task) { @@ -116,16 +101,16 @@ public class OcrTaskServiceImpl implements OcrTaskService { log.error("创建文档解析任务异常。e:",e); //失败直接发送结果 AppResultDoc entity = new AppResultDoc(); + entity.setTaskId((String)task.get(Constants.TASKID)); long now = System.currentTimeMillis(); - entity.setFinishTime(now); - entity.setLastEdit(now); + entity.setCreateTime(now); Map result = new HashMap(16); - result.put(Constants.CONTENT, "识别任务创建异常"); - result.put(Constants.WROD_COUNT, 0); + result.put(Constants.ERROR, "识别任务创建异常"); entity.setResult(result); entity.setStatus(2); - Map map = objectMapper.convertValue(entity, Map.class); - updateFields(task.get(Constants.TASKID).toString(),map); + entity.setDel(0); + //回传给api服务保存 + DownLoadUtil.doPost(saveUrl, JSONObject.toJSONString(entity)); } @@ -171,31 +156,33 @@ public class OcrTaskServiceImpl implements OcrTaskService { String parseContent = readWordFromBase64(fileContents); //成功 发送结果 AppResultDoc entity = new AppResultDoc(); + entity.setTaskId((String)task.get(Constants.TASKID)); long now = System.currentTimeMillis(); - entity.setFinishTime(now); - entity.setLastEdit(now); + entity.setCreateTime(now); + entity.setTaskId((String)task.get(Constants.TASKID)); Map result = new HashMap(16); result.put(Constants.CONTENT, parseContent); result.put(Constants.WROD_COUNT, parseContent.length()); entity.setResult(result); entity.setStatus(1); - Map map = objectMapper.convertValue(entity, Map.class); - updateFields(task.get(Constants.TASKID).toString(),map); + entity.setDel(0); + //回传给api服务保存 + DownLoadUtil.doPost(saveUrl, JSONObject.toJSONString(entity)); }else { //识别异常 log.error("文档识别异常:{}",resStr); //发送失败结果 AppResultDoc entity = new AppResultDoc(); + entity.setTaskId((String)task.get(Constants.TASKID)); long now = System.currentTimeMillis(); - entity.setFinishTime(now); - entity.setLastEdit(now); + entity.setCreateTime(now); Map result = new HashMap(16); - result.put(Constants.CONTENT, "识别失败"); - result.put(Constants.WROD_COUNT, 0); + result.put(Constants.ERROR, "识别失败"); entity.setResult(result); entity.setStatus(2); - Map map = objectMapper.convertValue(entity, Map.class); - updateFields(task.get(Constants.TASKID).toString(),map); + entity.setDel(0); + //回传给api服务保存 + DownLoadUtil.doPost(saveUrl, JSONObject.toJSONString(entity)); } @@ -204,16 +191,16 @@ public class OcrTaskServiceImpl implements OcrTaskService { log.error("创建文档解析任务异常。e:",e); //发送失败结果 AppResultDoc entity = new AppResultDoc(); + entity.setTaskId((String)task.get(Constants.TASKID)); long now = System.currentTimeMillis(); - entity.setFinishTime(now); - entity.setLastEdit(now); + entity.setCreateTime(now); Map result = new HashMap(16); - result.put(Constants.CONTENT, "源文件解析异常"); - result.put(Constants.WROD_COUNT, 0); + result.put(Constants.ERROR, "源文件解析异常"); entity.setResult(result); entity.setStatus(2); - Map map = objectMapper.convertValue(entity, Map.class); - updateFields(task.get(Constants.TASKID).toString(),map); + entity.setDel(0); + //回传给api服务保存 + DownLoadUtil.doPost(saveUrl, JSONObject.toJSONString(entity)); } } @@ -239,71 +226,6 @@ public class OcrTaskServiceImpl implements OcrTaskService { } - /** - * 节点数据局部修改 - * @param docId 文档ID - * @param fields 要修改的字段集合 - * @return boolean 是否成功 - */ - private boolean updateFields(String docId, Map fields){ - if(fields == null || fields.isEmpty()){ - log.warn("修改失败,fields为空"); - return false; - } - - CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(esUser, esPassword)); - - CloseableHttpClient httpClient = null; - try { - if(esUser != null && !esUser.trim().equals(Constants.EMPTY)){ - httpClient = HttpClients.custom() - .setDefaultCredentialsProvider(credentialsProvider) - .build(); - } else { - httpClient = HttpClients.custom().build(); - } - - // 拼接 ES _update URL - StringBuilder url = new StringBuilder(); - url.append(esUrl) - .append("/") - .append(indexName) - .append("/_update/") - .append(docId); - - HttpPost httpPost = new HttpPost(url.toString()); - - // 构造请求体,只更新指定字段 - Map docMap = new HashMap<>(); - docMap.put("doc", fields); - - StringEntity entity = new StringEntity(JSONObject.toJSONString(docMap), ContentType.APPLICATION_JSON); - httpPost.setEntity(entity); - - HttpResponse response = httpClient.execute(httpPost); - int statusCode = response.getStatusLine().getStatusCode(); - String responseBody = EntityUtils.toString(response.getEntity()); - - if(statusCode == 200){ - log.info("数据成功局部更新到索引:{},文档ID:{},更新字段:{}", indexName, docId, fields.keySet()); - return true; - } else { - log.error("数据局部更新失败:{},文档ID:{},ES响应:{}", indexName, docId, responseBody); - return false; - } - - } catch (Exception e){ - log.error("数据局部更新异常:", e); - return false; - } finally { - try { - if(httpClient != null) { - httpClient.close(); - } - } catch (Exception ignored){} - } - } public static void main(String[] args) throws Exception { diff --git a/opai-api/src/main/java/com/bw/opai/app/controller/AppController.java b/opai-api/src/main/java/com/bw/opai/app/controller/AppController.java index 40d3cbe..39446ac 100644 --- a/opai-api/src/main/java/com/bw/opai/app/controller/AppController.java +++ b/opai-api/src/main/java/com/bw/opai/app/controller/AppController.java @@ -12,6 +12,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import com.bw.opai.app.entity.AppResultDoc; import com.bw.opai.app.service.AppService; import com.bw.opai.common.Res; @@ -75,9 +76,19 @@ public class AppController { @GetMapping("/tasks") public Res getMyTasks( @RequestParam(value = "page", defaultValue = "1", required = false) Integer page, - @RequestParam(value = "size", defaultValue = "10", required = false) Integer size) { + @RequestParam(value = "size", defaultValue = "10", required = false) Integer size, + @RequestParam Boolean isData) { - return appService.getMyTasks(page, size); + return appService.getMyTasks(page, size,isData); + } + + /** + * app应用数据回写 + * @param appData + * @return + */ + @PostMapping("/datasave") + public Res appDataSave(@RequestBody AppResultDoc appData) { + return appService.dataSave(appData); } - } diff --git a/opai-api/src/main/java/com/bw/opai/app/dto/App.java b/opai-api/src/main/java/com/bw/opai/app/dto/App.java index 7fee3ca..29a4425 100644 --- a/opai-api/src/main/java/com/bw/opai/app/dto/App.java +++ b/opai-api/src/main/java/com/bw/opai/app/dto/App.java @@ -1,7 +1,18 @@ package com.bw.opai.app.dto; -import com.baomidou.mybatisplus.annotation.*; -import lombok.Data; import java.time.LocalDateTime; +import java.util.Map; + +import org.apache.ibatis.type.JdbcType; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler; + +import lombok.Data; /** * 应用表 @@ -10,7 +21,7 @@ import java.time.LocalDateTime; * @description */ @Data -@TableName("app") +@TableName(value = "app", autoResultMap = true) public class App { /** @@ -24,7 +35,7 @@ public class App { private Integer updateUserId; private String updateUser; - @TableField(fill = FieldFill.INSERT) + private LocalDateTime createTime; @TableField(fill = FieldFill.INSERT_UPDATE) @@ -57,4 +68,12 @@ public class App { * 应用接口地址 */ private String api; + + /** + * 输入信息 + */ + @TableField(typeHandler = JacksonTypeHandler.class) + private Map input; + + } diff --git a/opai-api/src/main/java/com/bw/opai/app/dto/Task.java b/opai-api/src/main/java/com/bw/opai/app/dto/Task.java new file mode 100644 index 0000000..9a9721d --- /dev/null +++ b/opai-api/src/main/java/com/bw/opai/app/dto/Task.java @@ -0,0 +1,72 @@ +package com.bw.opai.app.dto; + +import java.time.LocalDateTime; +import java.util.List; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.bw.opai.app.entity.AppResultDoc; + +import lombok.Data; + +/** + * 任务表 + * @author jian.mao + * @date 2026年1月7日 + * @description + */ +@Data +@TableName("task") +public class Task { + + /** + * 任务id + */ + @TableId(value = "id") + private String id; + + /** + * 应用id + */ + private Integer appId; + + + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private LocalDateTime createTime; + + /** + * 删除标识 + */ + private Integer del; + + /** + * 最后修改时间 + */ + private LocalDateTime lastEdit; + + /** + * 任务状态 + */ + private Integer status; + + /** + * 用户标识 + */ + private String userId; + + /** + * 完成时间 + */ + private LocalDateTime finishTime; + + /** + * 任务数据(非表字段) + */ + @TableField(exist = false) + private List data; +} diff --git a/opai-api/src/main/java/com/bw/opai/app/entity/AppResultDoc.java b/opai-api/src/main/java/com/bw/opai/app/entity/AppResultDoc.java index 3b4b029..5ddd238 100644 --- a/opai-api/src/main/java/com/bw/opai/app/entity/AppResultDoc.java +++ b/opai-api/src/main/java/com/bw/opai/app/entity/AppResultDoc.java @@ -17,33 +17,22 @@ public class AppResultDoc implements Serializable { private static final long serialVersionUID = 1L; - /** 应用ID */ - private Integer appId; + /** 任务ID */ + private String taskId; - /** 应用名称 */ - private String appName; - - /** 用户ID */ - private String userId; - - /** 任务参数(可索引) */ - private Map task; + /** 应用id */ + private String appId; + + /** 状态 0 进行中,1成功,2失败 */ + private Integer status; /** 创建时间(毫秒时间戳) */ private Long createTime; - /** 完成时间(毫秒时间戳) */ - private Long finishTime; - - /** 执行状态 */ - private Integer status; - /** 执行结果(可索引) */ private Map result; /** 逻辑删除标识:0-未删除 1-已删除 */ private Integer del; - /** 最后修改时间(毫秒时间戳) */ - private Long lastEdit; } diff --git a/opai-api/src/main/java/com/bw/opai/app/mapper/TaskMapper.java b/opai-api/src/main/java/com/bw/opai/app/mapper/TaskMapper.java new file mode 100644 index 0000000..5e812a0 --- /dev/null +++ b/opai-api/src/main/java/com/bw/opai/app/mapper/TaskMapper.java @@ -0,0 +1,18 @@ +package com.bw.opai.app.mapper; + +import org.apache.ibatis.annotations.Mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.bw.opai.app.dto.Task; + +/** + * 应用mapper + * @author jian.mao + * @date 2026年1月4日 + * @description + */ +@Mapper +public interface TaskMapper extends BaseMapper { + + +} diff --git a/opai-api/src/main/java/com/bw/opai/app/service/AppService.java b/opai-api/src/main/java/com/bw/opai/app/service/AppService.java index fa65630..ed35f17 100644 --- a/opai-api/src/main/java/com/bw/opai/app/service/AppService.java +++ b/opai-api/src/main/java/com/bw/opai/app/service/AppService.java @@ -2,6 +2,7 @@ package com.bw.opai.app.service; import java.util.Map; +import com.bw.opai.app.entity.AppResultDoc; import com.bw.opai.common.Res; /** @@ -40,5 +41,7 @@ public interface AppService { * @param size * @return */ - public Res getMyTasks(Integer page, Integer size); + public Res getMyTasks(Integer page, Integer size,Boolean isData); + + public Res dataSave(AppResultDoc appData); } diff --git a/opai-api/src/main/java/com/bw/opai/app/service/impl/AppServiceImpl.java b/opai-api/src/main/java/com/bw/opai/app/service/impl/AppServiceImpl.java index f2fc42b..56d2fe1 100644 --- a/opai-api/src/main/java/com/bw/opai/app/service/impl/AppServiceImpl.java +++ b/opai-api/src/main/java/com/bw/opai/app/service/impl/AppServiceImpl.java @@ -1,9 +1,11 @@ package com.bw.opai.app.service.impl; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.UUID; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; @@ -22,11 +24,14 @@ import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.bw.opai.app.dto.App; +import com.bw.opai.app.dto.Task; import com.bw.opai.app.entity.AppResultDoc; import com.bw.opai.app.mapper.AppMapper; +import com.bw.opai.app.mapper.TaskMapper; import com.bw.opai.app.service.AppService; import com.bw.opai.common.Res; import com.bw.opai.utils.Constants; @@ -43,6 +48,8 @@ public class AppServiceImpl implements AppService { private final AppMapper appMapper; + private final TaskMapper taskMapper; + @Value("${elasticsearch.url}") private String esUrl; @@ -111,16 +118,13 @@ public class AppServiceImpl implements AppService { if (appId == null) { return Res.fail("应用ID不能为空"); } - //任务id校验 - String taskId = param.get("taskId") == null||param.get("taskId").toString().equals("")? null : param.get("taskId").toString(); - if (taskId == null) { - return Res.fail("任务ID不能为空"); - } // 伪示例:根据 ID 查询应用并启动 App app = appMapper.selectById(appId); if (app == null || app.getDel() != 0) { return Res.fail("未找到对应应用"); } + String taskId = UUID.randomUUID().toString().replace("-", Constants.EMPTY); + param.put(Constants.TASKID, taskId); //应用调用 String appUrl = app.getApi(); String downloadRes = DownLoadUtil.doPost(appUrl, JSONObject.toJSONString(param)); @@ -129,40 +133,196 @@ public class AppServiceImpl implements AppService { log.error("启动应用请求异常, param={},download error:{}", param, downloadRes); return Res.fail("启动应用请求异常"); } - //任务记录写入es - long now = System.currentTimeMillis(); - - AppResultDoc esEntity = new AppResultDoc(); - esEntity.setAppId(app.getId()); - esEntity.setAppName(app.getName()); - //用户token -- 先给默认值 - esEntity.setUserId("1"); - - esEntity.setTask(param); - esEntity.setResult(null); - - esEntity.setCreateTime(now); - esEntity.setFinishTime(null); - // 运行中 0 是运行中,1是完成,2是失败 - esEntity.setStatus(0); - esEntity.setDel(0); - esEntity.setLastEdit(now); - - // ---------- 写入 ES ---------- - boolean isSuccess = save(esEntity, taskId); - if(!isSuccess) { - //记录写入失败,直接返回错误信息 - log.error("启动应用记录写入异常, param={}", param); - return Res.fail("启动应用记录写入异常"); - } + //任务录入表中 + Task task = new Task(); + task.setId(taskId); + task.setCreateTime(LocalDateTime.now()); + task.setAppId(appId); + task.setDel(0); + task.setStatus(0); + task.setUserId("1"); + taskMapper.insert(task); // ---------- 返回 ---------- - return Res.ok(esEntity); + return Res.ok(task); } catch (Exception e) { log.error("启动应用未知异常, param={}", param, e); return Res.fail("启动应用未知异常"); } } + + + @Override + public Res getMyTasks(Integer page, Integer size,Boolean isData) { + + if (page == null || page < 1) { + page = 1; + } + if (size == null || size < 1 || size > 100) { + size = 10; + } + + // 从登录上下文获取 userId(你项目里已有) 先写死 + String userId = "1"; + if (userId == null || userId.trim().equals("")) { + return Res.fail("未获取到用户信息"); + } + + try { + Page pageParam = new Page<>(page, size); + + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(Task::getDel, 0) + .eq(userId != null, Task::getUserId, userId) + .orderByDesc(Task::getCreateTime); + + Page result = taskMapper.selectPage(pageParam, wrapper); + if(isData) { + log.info("任务关联数据开始~"); + List tasks = result.getRecords(); + for (Task task : tasks) { + String taskId = task.getId(); + CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials( + AuthScope.ANY, + new UsernamePasswordCredentials(esUser, esPassword) + ); + + CloseableHttpClient httpClient = null; + try { + if (esUser != null && !esUser.trim().equals("")) { + httpClient = HttpClients.custom() + .setDefaultCredentialsProvider(credentialsProvider) + .build(); + } else { + httpClient = HttpClients.custom().build(); + } + + // ================== 构建查询 DSL ================== + + Map query = new HashMap(); + // must 条件 + List> mustList = new ArrayList>(); + + Map termDel = new HashMap(); + termDel.put("del", 0); + Map termDelWrap = new HashMap(); + termDelWrap.put("term", termDel); + mustList.add(termDelWrap); + //任务id查询条件 + Map termTaskId = new HashMap(); + termTaskId.put("taskId", taskId); + Map termTaskIdWrap = new HashMap(); + termTaskIdWrap.put("term", termTaskId); + mustList.add(termTaskIdWrap); + + Map bool = new HashMap(); + bool.put("must", mustList); + + Map queryBody = new HashMap(); + queryBody.put("bool", bool); + + query.put("query", queryBody); + + // sort + List> sortList = new ArrayList>(); + Map order = new HashMap(); + order.put("order", "desc"); + Map sortField = new HashMap(); + sortField.put("createTime", order); + sortList.add(sortField); + query.put("sort", sortList); + log.info("任务数据查询条件:{}",JSONObject.toJSONString(query)); + + // ================== 发起 HTTP 请求 ================== + StringBuffer host = new StringBuffer(); + host.append(esUrl) + .append("/") + .append(indexName) + .append("/_search"); + + HttpPost httpPost = new HttpPost(host.toString()); + httpPost.setHeader("Content-Type", "application/json"); + + StringEntity entity = new StringEntity( + JSONObject.toJSONString(query), + ContentType.APPLICATION_JSON + ); + httpPost.setEntity(entity); + + HttpResponse response = httpClient.execute(httpPost); + int statusCode = response.getStatusLine().getStatusCode(); + String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8"); + + if (statusCode != 200) { + log.error("ES 查询失败 status={}, body={}", statusCode, responseBody); + continue; + } + + // ================== 解析返回 ================== + JSONObject json = JSONObject.parseObject(responseBody); + JSONObject hits = json.getJSONObject("hits"); + + List list = new ArrayList(); + JSONArray hitList = hits.getJSONArray("hits"); + for (int i = 0; i < hitList.size(); i++) { + JSONObject source = hitList.getJSONObject(i).getJSONObject("_source"); + AppResultDoc item = source.toJavaObject(AppResultDoc.class); + list.add(item); + } + task.setData(list); + + } catch (Exception e) { + log.error("查询用户任务失败 userId={}", userId, e); + continue; + } finally { + if (httpClient != null) { + try { + httpClient.close(); + } catch (Exception ignored) {} + } + } + } + } + log.info("任务查询成功"); + return Res.page(result); + } catch (Exception e) { + log.error("查询任务列表失败", e); + return Res.fail("查询任务列表失败"); + } + + } + @Override + public Res dataSave(AppResultDoc appData) { + String docId = UUID.randomUUID().toString().replace("-", Constants.EMPTY); + // ---------- 写入 ES ---------- + boolean isSuccess = save(appData,docId); + if(!isSuccess) { + //记录写入失败,直接返回错误信息 + log.error("启动应用记录写入异常, appData={}", appData); + Task task = new Task(); + task.setId(appData.getTaskId()); + task.setStatus(appData.getStatus()); + task.setFinishTime(LocalDateTime.now()); + task.setStatus(2); + task.setLastEdit(LocalDateTime.now()); + taskMapper.updateById(task); + return Res.fail("应用数据写入异常"); + }else { + log.info("任务状态更新"); + Task task = new Task(); + task.setId(appData.getTaskId()); + task.setStatus(appData.getStatus()); + task.setFinishTime(LocalDateTime.now()); + task.setStatus(appData.getStatus()); + task.setLastEdit(LocalDateTime.now()); + taskMapper.updateById(task); + } + + + return Res.ok(appData); + } + /** * 节点数据持久化 * @param esEntity @@ -204,10 +364,10 @@ public class AppServiceImpl implements AppService { int code = 201; int updateCode = 200; if (statusCode == code) { - log.info("数据成功写入到索引:{},文档ID:{},appid:{},userId:{}",indexName,docId,esEntity.getAppId(),esEntity.getUserId()); + log.info("数据成功写入到索引:{},文档ID:{},appid:{}",indexName,docId,esEntity.getAppId()); return true; }else if(statusCode == updateCode){ - log.info("数据成功更新到索引:{},文档ID:{},appid:{},userId:{}",indexName,docId,esEntity.getAppId(),esEntity.getUserId()); + log.info("数据成功更新到索引:{},文档ID:{},appid:{}",indexName,docId,esEntity.getAppId()); return true; } else { log.error("数据写入失败:{},文档ID:{},appid:{},es响应内容:{}",indexName,docId,esEntity.getAppId(),responseBody); @@ -225,134 +385,4 @@ public class AppServiceImpl implements AppService { } } - @Override - public Res getMyTasks(Integer page, Integer size) { - - if (page == null || page < 1) { - page = 1; - } - if (size == null || size < 1 || size > 100) { - size = 10; - } - - // 从登录上下文获取 userId(你项目里已有) 先写死 - String userId = "1"; - if (userId == null || userId.trim().equals("")) { - return Res.fail("未获取到用户信息"); - } - - CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials( - AuthScope.ANY, - new UsernamePasswordCredentials(esUser, esPassword) - ); - - CloseableHttpClient httpClient = null; - try { - if (esUser != null && !esUser.trim().equals("")) { - httpClient = HttpClients.custom() - .setDefaultCredentialsProvider(credentialsProvider) - .build(); - } else { - httpClient = HttpClients.custom().build(); - } - - // ================== 构建查询 DSL ================== - int from = (page - 1) * size; - - Map query = new HashMap(); - query.put("from", from); - query.put("size", size); - - // must 条件 - List> mustList = new ArrayList>(); - - Map termUser = new HashMap(); - termUser.put("userId", userId); - Map termUserWrap = new HashMap(); - termUserWrap.put("term", termUser); - mustList.add(termUserWrap); - - Map termDel = new HashMap(); - termDel.put("del", 0); - Map termDelWrap = new HashMap(); - termDelWrap.put("term", termDel); - mustList.add(termDelWrap); - - Map bool = new HashMap(); - bool.put("must", mustList); - - Map queryBody = new HashMap(); - queryBody.put("bool", bool); - - query.put("query", queryBody); - - // sort - List> sortList = new ArrayList>(); - Map order = new HashMap(); - order.put("order", "desc"); - Map sortField = new HashMap(); - sortField.put("createTime", order); - sortList.add(sortField); - query.put("sort", sortList); - - // ================== 发起 HTTP 请求 ================== - StringBuffer host = new StringBuffer(); - host.append(esUrl) - .append("/") - .append(indexName) - .append("/_search"); - - HttpPost httpPost = new HttpPost(host.toString()); - httpPost.setHeader("Content-Type", "application/json"); - - StringEntity entity = new StringEntity( - JSONObject.toJSONString(query), - ContentType.APPLICATION_JSON - ); - httpPost.setEntity(entity); - - HttpResponse response = httpClient.execute(httpPost); - int statusCode = response.getStatusLine().getStatusCode(); - String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8"); - - if (statusCode != 200) { - log.error("ES 查询失败 status={}, body={}", statusCode, responseBody); - return Res.fail("ES 查询失败"); - } - - // ================== 解析返回 ================== - JSONObject json = JSONObject.parseObject(responseBody); - JSONObject hits = json.getJSONObject("hits"); - - Long total = hits.getJSONObject("total").getLong("value"); - - List list = new ArrayList(); - JSONArray hitList = hits.getJSONArray("hits"); - for (int i = 0; i < hitList.size(); i++) { - JSONObject source = hitList.getJSONObject(i).getJSONObject("_source"); - AppResultDoc item = source.toJavaObject(AppResultDoc.class); - list.add(item); - } - - Map result = new HashMap(); - result.put("page", page); - result.put("size", size); - result.put("total", total); - result.put("list", list); - - return Res.ok(result); - - } catch (Exception e) { - log.error("查询用户任务失败 userId={}", userId, e); - return Res.fail("查询任务失败"); - } finally { - if (httpClient != null) { - try { - httpClient.close(); - } catch (Exception ignored) {} - } - } - } - } diff --git a/opai-api/src/main/java/com/bw/opai/utils/Constants.java b/opai-api/src/main/java/com/bw/opai/utils/Constants.java index 6e2afe4..958bd38 100644 --- a/opai-api/src/main/java/com/bw/opai/utils/Constants.java +++ b/opai-api/src/main/java/com/bw/opai/utils/Constants.java @@ -16,4 +16,9 @@ public class Constants { * 请求失败结果前缀 */ public static final String DOWNLOAD_ERROR_SUFFIX = "Download failed error is:"; + + /** + * 任务id常量 + */ + public static final String TASKID = "taskId"; }