linfutong лет назад: 2
Родитель
Сommit
de055a0c25

+ 0 - 1
zd-model/src/main/java/com/zd/model/domain/R.java

@@ -2,7 +2,6 @@ package com.zd.model.domain;
 
 
 import com.zd.model.constant.HttpStatus;
-
 import java.io.Serializable;
 
 /**

+ 40 - 4
zd-modules/zd-algorithm/src/main/java/com/zd/alg/forward/controller/SignInCheckController.java

@@ -12,6 +12,8 @@ import com.zd.common.core.exception.ServiceException;
 import com.zd.common.core.redis.RedisService;
 import com.zd.common.core.utils.Assert;
 import com.zd.common.swagger.config.Knife4jConfiguration;
+import com.zd.model.constant.BaseConstants;
+import com.zd.model.constant.HttpStatus;
 import com.zd.model.domain.R;
 import com.zd.model.entity.Algorithm;
 import io.swagger.annotations.Api;
@@ -67,6 +69,11 @@ public class SignInCheckController {
     @ApiOperation(value = "进入项验证")
     @PostMapping("/{code}/{id}")
     public R checkIn(@ApiParam("进出记录ID") @PathVariable("id") Long id, @ApiParam("验证类型编码") @PathVariable("code") String code, @RequestParam("file") MultipartFile file) {
+        //检查签到
+        R result = checkSignInOrOut(id);
+        if (result.getCode() != HttpStatus.SUCCESS) {
+            return result;
+        }
         return checkService.checkAndCommit(code, file, id);
     }
 
@@ -81,6 +88,11 @@ public class SignInCheckController {
     public R checkInAll(@ApiParam("进出记录ID") @RequestParam("id") Long id,
                         @ApiParam("图片文件") @RequestParam("file") MultipartFile file,
                         @ApiParam("实验室ID") @RequestParam("subId") Long subId) {
+        //检查签到
+        R result = checkSignInOrOut(id);
+        if (result.getCode() != HttpStatus.SUCCESS) {
+            return result;
+        }
         return checkService.checkAndCommit(id, file, subId);
     }
 
@@ -94,6 +106,11 @@ public class SignInCheckController {
     @ApiOperation(value = "进入项验证:mock方法")
     @PostMapping("/mock/{code}/{id}")
     public R checkInMock(@ApiParam("进出记录ID") @PathVariable("id") Long id, @ApiParam("验证类型编码") @PathVariable("code") String code, @RequestParam("file") MultipartFile file) {
+        //检查签到
+        R result = checkSignInOrOut(id);
+        if (result.getCode() != HttpStatus.SUCCESS) {
+            return result;
+        }
         return checkService.mockTest(code, file, id);
     }
 
@@ -127,11 +144,11 @@ public class SignInCheckController {
     @PostMapping("/alarmCallBack")
     public R fireCallBack(@RequestBody VideoRequestData videoRequestData) {
         Integer aid = videoRequestData.getAid();
-        if (aid!=null){
-            if (aid.equals(9610)){
-                logger.info("=====================>测试回调了。。。{}",videoRequestData.getAlgo_name());
+        if (aid != null) {
+            if (aid.equals(9610)) {
+                //logger.info("=====================>测试回调了。。。{}",videoRequestData.getAlgo_name());
                 checkService.sendAlarm(videoRequestData);
-            }else if (aid.equals(9690)){
+            } else if (aid.equals(9690)) {
                 checkService.playMp3();
             }
         }
@@ -163,4 +180,23 @@ public class SignInCheckController {
     public R checkFire(@ApiParam("图片文件") @RequestParam("file") MultipartFile file) {
         return R.ok(fireImageService.catchImage(file));
     }
+
+    /**
+     * 检查签到/签退
+     * @param id
+     * @return
+     */
+    private R checkSignInOrOut(Long id) {
+        //检查签到
+        Long value = redisService.getCacheObject(BaseConstants.SINGIN_id_KEY + id);
+        if (value != null) {
+            //刷新key
+            boolean expire = redisService.expire(BaseConstants.SINGIN_id_KEY + id, BaseConstants.SINGIN_OUT_TIME);
+            if (!expire) {
+                return R.fail(600, "签到&签出已超时,请刷卡重试!");
+            }
+            return R.ok();
+        }
+        return R.fail(600, "签到&签出已超时,请刷卡重试!");
+    }
 }

+ 43 - 228
zd-modules/zd-algorithm/src/main/java/com/zd/alg/forward/serivce/CheckService.java

@@ -3,7 +3,6 @@ package com.zd.alg.forward.serivce;
 import cn.hutool.core.text.CharSequenceUtil;
 import cn.hutool.core.util.RandomUtil;
 import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import com.zd.alg.forward.config.AlgorithmYml;
 import com.zd.alg.forward.domain.*;
@@ -23,6 +22,7 @@ import com.zd.common.core.utils.ServletUtils;
 import com.zd.common.core.utils.StringUtils;
 import com.zd.laboratory.api.feign.RemoteLaboratoryService;
 import com.zd.model.constant.BaseConstants;
+import com.zd.model.constant.HttpStatus;
 import com.zd.model.constant.SecurityConstants;
 import com.zd.model.domain.R;
 import com.zd.model.entity.Algorithm;
@@ -56,11 +56,6 @@ public class CheckService {
     Logger logger = LoggerFactory.getLogger(CheckService.class);
     @Resource(name = "restTemplateLocal")
     private RestTemplate restTemplateLocal;
-    /**
-     * 上传文件存储在本地的根路径
-     */
-    @Value("${file.path:/home/AIPIC}")
-    private String localFilePath;
 
     @Autowired
     private AlgorithmYml algorithmYml;
@@ -95,15 +90,9 @@ public class CheckService {
     public R checkAndCommit(Long id, MultipartFile file, Long subId) {
         try {
             int alarmNum = 0;
-            //========= 请求超时验证部分开始 ===========
-            //600 则代表退出验证流程 需要重新刷卡
-            R<Long> fail = getObjectR(id);
-            if (fail.getCode() != 200) {
-                return fail;
-            }
             //根据实验室id查询检查项
             R<Map<Object, Object>> subject = laboratoryService.getCheckInfo(subId);
-            if (subject.getCode() != 200) {
+            if (subject.getCode() != HttpStatus.SUCCESS) {
                 return subject;
             }
             Map<Object, Object> map = subject.getData();
@@ -114,8 +103,7 @@ public class CheckService {
             //上传原始图片
             String orgImgUrl = "";
             R<SysFile> r = remoteFileService.upload(file);
-            //logger.info("【调用算法服务】 原文件上传结果:"+JSONObject.toJSONString(r));
-            if (r.getCode() == 200) {
+            if (r.getCode() == HttpStatus.SUCCESS) {
                 orgImgUrl = r.getData().getUrl();
             }
             String labSkipped = "0";
@@ -297,44 +285,36 @@ public class CheckService {
      * @param id 进出记录ID
      */
     public R checkAndCommit(String code, MultipartFile file, Long id) {
-        //========= 请求超时验证部分开始 ===========
-        //600 则代表退出验证流程 需要重新刷卡
-        R<Long> fail = getObjectR(id);
-        if (fail.getCode() != 200) {
-            return fail;
+        //上传原始图片
+        String orgImgUrl = "";
+        R<SysFile> r = remoteFileService.upload(file);
+        if (r.getCode() == HttpStatus.SUCCESS) {
+            orgImgUrl = r.getData().getUrl();
         }
-        //========= 请求超时验证部分结束 ===========
         //========= 获取算法INFO ===========
         AlgorithmYml.CheckValid checkValid = algorithmYml.getCheckValid(Integer.valueOf(code));
-        //=========发送验证信息到算法服务开始
-        JSONObject send = null;
-        try {
-            send = send(file, checkValid, id);
-        } catch (Exception e) {
-            logger.error(e.getMessage());
-            e.printStackTrace();
+        //添加一条算法请求记录
+        R alg = insertRequestRecordLog(orgImgUrl, 0L, checkValid);
+        logger.info("【调用算法服务】 添加算法调用日志,添加结果:"+JSONObject.toJSONString(alg));
+
+        File toFile = multipartFileToFile(file);
+        //请求算法服务
+        MultiValueMap<String, Object> params = getStringObjectMultiValueMap(checkValid, String.valueOf(id));
+        HttpEntity<MultiValueMap<String, Object>> files = getHttpEntityMap(toFile, params);
+        ImgPostResponse<AnalysisReturnData> send = HttpUtils.sendV5(restTemplateLocal, files, algorithmYml);
+        AlgorithmResponseResult responseResult = getResponseResult(send);
+        //添加成功,更新算法日志记录
+        if (alg.getCode() == 200) {
+            updateRequestRecordLog(alg.getData() != null?Long.valueOf(alg.getData()+""):null, responseResult);
+            logger.info("【调用算法服务】 更新算法调用日志记录");
         }
-        //=========发送验证信息到算法服务结束
-        //=========算法服务返回结果验证开始
-        R apply = R.fail("算法服务错误,请重试!");
-        Boolean f = false;
-        try {
-            if (send == null || send.getInteger("status_code") != 1000L) {
-                apply = R.fail("算法服务错误,请重试!");
-                return apply;
-            }
-            Map<String, Object> result = null;
-            try {
-                result = send.getJSONObject("data").getJSONObject("result").getInnerMap();
-            } catch (Exception e) {
-                e.printStackTrace();
-                apply = R.fail("算法服务返回数据错误,请联系管理员!");
-                return apply;
-            }
-            //todo  获取 检测结果
-            apply = checkValid.getCheckResultValid().apply(result);
-            f = apply.getCode() == 200;
-            if (!f && algorithmYml.getJumpThreshold() != -1) {
+        //插入记录数据,异步请求远程接口
+        String msg = (responseResult.getCode() == 1000 && responseResult.getIsPass())?"解析成功":"解析失败";
+        send(code, id, responseResult.getIsPass(), msg);
+        //判断算法
+        if (responseResult.getCode() == 1000) {
+            boolean isPass = responseResult.getIsPass();
+            if (!isPass && algorithmYml.getJumpThreshold() != -1) {
                 //如果没有通过则次数加一
                 //键为前缀+签到id +下划线+验证类型
                 String key = BaseConstants.SINGIN_CHECK_JUMP_KEY + id + "_" + code;
@@ -342,47 +322,18 @@ public class CheckService {
                 redisService.expire(key, BaseConstants.SINGIN_OUT_TIME);
                 if (increment >= algorithmYml.getJumpThreshold()) {
                     //黎晨这里让把跳过时状态码改为700,所以700的含义为检查失败并且跳过
-                    apply.setCode(700);
+                    return R.fail(700,"算法服务错误,请重试!");
                 }
             }
-        } catch (Exception ex) {
-            ex.printStackTrace();
-            apply = R.fail("算法服务返回数据错误,请联系管理员!");
-            return apply;
-        } finally {
-           //无论成功失败,插入记录数据,异步请求远程接口
-            send(code, id, f, apply.getMsg());
-        }
-        //=========算法服务返回结果验证结束
-        logger.info(apply.toString());
-        if (apply.getCode() == 200) {
-            //加奖励分
-            // laboratoryService.addRecord();
-        }
-        return apply;
-    }
-
-    /**
-     * 三合一
-     *
-     * @param ids
-     * @param file
-     * @param codes
-     * @return
-     */
-    public R<Map<Object, String>> checkInAll(Long[] ids, MultipartFile file[], String codes) {
-        Map<Object, String> result = new HashMap<>();
-        String[] codesArrs = codes.split(",");
-        for (int i = 0; i < codesArrs.length; i++) {
-            R r = checkAndCommit(codesArrs[i], file[i], ids[i]);
-            AlgorithmYml.CheckValid checkValid = algorithmYml.getCheckValid(Integer.valueOf(codesArrs[i]));
-            result.put(checkValid.getAlgoId(), r.getMsg() == null ? "通过" : r.getMsg());
-
+            if (responseResult.getIsPass()) {
+                //加奖励分
+                // laboratoryService.addRecord();
+            }
+            return R.ok();
         }
-        return R.ok(result);
+        return R.fail("算法服务错误,请重试!");
     }
 
-
     public Algorithm Covert(Map<String, Object> data) {
         Algorithm algorithm = new Algorithm();
         algorithm.setAlgorithmType(data.get("type").toString());
@@ -395,22 +346,6 @@ public class CheckService {
         return algorithm;
     }
 
-    public Algorithm CovertV5(Map<String, Object> data) {
-        Algorithm algorithm = new Algorithm();
-        algorithm.setId(Long.valueOf(data.get("id").toString()));
-        algorithm.setAlgorithmType(data.get("type").toString());
-        algorithm.setAlgorithmResult(data.get("src_img").toString());
-        algorithm.setSubId(Long.valueOf(data.get("aid").toString()));
-        algorithm.setSignId(Long.valueOf(data.get("cid").toString()));
-        algorithm.setAlgorithmName(data.get("algorithmName").toString());
-        algorithm.setIsAlarm(Integer.parseInt(data.get("isAlarm").toString()));
-        algorithm.setOriginalImg(data.get("originalImg").toString());
-        algorithm.setRespData(data.get("requestData").toString());
-        algorithm.setUpdateTime(new Date());
-        algorithm.setStatus(0);
-        return algorithm;
-    }
-
     /**
      * @param algorithmResult
      * @param type
@@ -485,25 +420,8 @@ public class CheckService {
     }
 
 
-    private R<Long> getObjectR(Long id) {
-        Long subId = redisService.getCacheObject(BaseConstants.SINGIN_id_KEY + id);
-        if (subId == null) {
-            return R.fail(600, "签到&签出已超时,请重新刷卡重试!");
-        }
-        //刷新key
-        boolean expire = redisService.expire(BaseConstants.SINGIN_id_KEY + id, 120);
-        if (!expire) {
-            return R.fail(600, "签到&签出已超时,请重新刷卡重试!");
-        }
-        return R.ok(subId);
-    }
-
     //给黎晨用的模拟方法 他让给他mock个方法测试
     public R mockTest(String code, MultipartFile file, Long id) {
-        R<Long> objectR = getObjectR(id);
-        if (objectR.getCode() != 200) {
-            return objectR;
-        }
         //随机成功或失败
         Boolean f = RandomUtil.randomInt(0, 2) == 0;
         //无论成功失败,插入记录数据,异步请求远程接口
@@ -525,7 +443,6 @@ public class CheckService {
 
     }
 
-
     public void send(String code, Long id, Boolean f, String msg) {
         String token = Objects.requireNonNull(ServletUtils.getRequest()).getHeader(SecurityConstants.TOKEN_AUTHENTICATION);
         if (CharSequenceUtil.isBlank(token)) {
@@ -535,26 +452,6 @@ public class CheckService {
     }
 
     /**
-     * 获取算法请求地址
-     *
-     * @param checkValid
-     * @param id
-     * @return
-     */
-    private String getPostUrl(AlgorithmYml.CheckValid checkValid, Long id) {
-        //设置请求体,注意是LinkedMultiValueMap
-        MultiValueMap<String, Object> params = getStringObjectMultiValueMap(checkValid, String.valueOf(id));
-        Set<String> keySet = params.keySet();
-        StringBuffer stb = new StringBuffer();
-        for (String key : keySet) {
-            stb.append("&" + key + "=" + params.get(key).get(0).toString());
-        }
-        String paramUrl = algorithmYml.getImgPostUrl() + String.valueOf(stb).replaceFirst("&", "?");
-        logger.info(paramUrl);
-        return paramUrl;
-    }
-
-    /**
      * 图片算法请求参数
      *
      * @param file
@@ -562,17 +459,13 @@ public class CheckService {
      * @return
      * @throws IOException
      */
-
-    public JSONObject send(MultipartFile file, AlgorithmYml.CheckValid checkValid, Long id) throws IOException {
+    public JSONObject send(MultipartFile file, AlgorithmYml.CheckValid checkValid, Long id) {
         //设置请求头
         HttpHeaders headers = new HttpHeaders();
         headers.setContentType(MediaType.MULTIPART_FORM_DATA);
-        File uploadFile = null;
         try {
-            // 文件本地存储收集
-            FileUploadUtils.upload(localFilePath, file);
             //MultipartFile 转为临时文件
-            uploadFile = multipartFileToFile(file);
+            File uploadFile = multipartFileToFile(file);
             //文件转为文件系统资源
             FileSystemResource fileSystemResource = new FileSystemResource(uploadFile);
             //设置请求体,注意是LinkedMultiValueMap
@@ -583,15 +476,13 @@ public class CheckService {
             //用HttpEntity封装整个请求报文
             HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(params, headers);
             String paramUrl = algorithmYml.getImgPostUrl();
-            logger.info(paramUrl);
+            //logger.info(paramUrl);
             JSONObject body = restTemplateLocal.postForObject(paramUrl, files, JSONObject.class);
-            logger.info(body.toJSONString());
+            //logger.info(body.toJSONString());
             return body;
-        } finally {
-            //删除临时文件
-//            if (uploadFile != null) {
-//                uploadFile.delete();
-//            }
+        } catch (Exception e){
+            logger.error("【算法服务】 send方法执行异常,异常信息:",e);
+            return null;
         }
     }
 
@@ -623,80 +514,4 @@ public class CheckService {
             return null;
         }
     }
-
-    /**
-     * 存储数据
-     *
-     * @param send
-     * @param checkValid
-     */
-    private R saveAlgorithm(ImgPostResponse<DataPostAnalysisRespDto> send, AlgorithmYml.CheckValid checkValid) {
-        DataPostAnalysisRespDto analysisRespDto = send.getData();
-        List<AnalysisData> analysisDatas = analysisRespDto.getAnalysisDatas();
-        if (!analysisDatas.isEmpty()) {
-            for (AnalysisData data : analysisDatas) {
-                String picture = data.getRet_image();
-                String header = "data:image/jpeg;base64," + picture;
-                MultipartFile multipartFile = Base64DecodedMultipartFile.base64ToMultipart(header);
-                R<SysFile> sysFileR = remoteFileService.upload(multipartFile);
-                String imageUrl = sysFileR.getData().getUrl();
-                Map<String, Object> result = (Map<String, Object>) data.getResult();
-                Map<String, Object> map = new HashMap<>();
-                Map<String, Object> algorithmData = (Map<String, Object>) result.get("algorithm_data");
-                Map<String, Object> modelResult = (Map<String, Object>) result.get("model_data");
-                List<Map<String, Object>> objects = (List<Map<String, Object>>) modelResult.get("objects");
-                if (algorithmData.getOrDefault("is_alert", "").toString().equals("false") && objects.size() > 0) {
-                    map.put("isAlarm", 0);
-                } else {
-                    map.put("isAlarm", 1);
-                }
-                map.put("did", checkValid.getDid());
-                map.put("aid", checkValid.getAlgoId());
-                map.put("src_img", imageUrl);
-                map.put("type", "image");
-                map.put("algorithmName", checkValid.getAlgorithmName());
-                return laboratoryService.saveData(Covert(map));
-            }
-        }
-        logger.error("接口数据返回异常");
-        throw new ServiceException("接口数据返回异常");
-    }
-
-
-    /**
-     * 存储数据
-     * @param send
-     * @param checkValid
-     */
-    private R saveAlgorithmV5(Long id,MultipartFile file,ImgPostResponse<AnalysisReturnData> send,AlgorithmYml.CheckValid checkValid){
-        String picture = send.getData().getRet_image();
-        String header = "data:image/jpeg;base64,"+picture;
-        MultipartFile multipartFile = Base64DecodedMultipartFile.base64ToMultipart(header);
-        R<SysFile> sysFileR = remoteFileService.upload(multipartFile);
-        String imageUrl = sysFileR.getData().getUrl();
-        logger.info("==================================imageUrl:"+imageUrl);
-        AnalysisReturnData data =  send.getData();
-        Map<String, Object> map =new HashMap<>();
-        Map<String, Object> result =(Map<String, Object>)data.getResult();
-        Map<String, Object> algorithmData = (Map<String, Object>) result.get("algorithm_data");
-        Map<String, Object> modelResult = (Map<String, Object>) result.get("model_data");
-        List<Map<String, Object>> objects = (List<Map<String, Object>>) modelResult.get("objects");
-        if(algorithmData.getOrDefault("is_alert", "").toString().equals("false") && objects.size()>0){
-            map.put("isAlarm", 0);
-        }else{
-            map.put("isAlarm", 1);
-        }
-        map.put("isAlarm", 1);
-        map.put("aid", data.getAid());
-        map.put("cid", data.getCid());
-        map.put("src_img", imageUrl);
-        //map.put("originalImg", originalUrl);
-        map.put("type", "image");
-        map.put("algorithmName", checkValid.getAlgorithmName());
-        map.put("id",id);
-        map.put("requestData", JSONObject.toJSONString(send));
-        logger.info("=======================map.tostring()"+map.toString());
-        return laboratoryService.saveAlgorithmData(CovertV5(map));
-       // return laboratoryService.update(CovertV5(map));
-    }
 }

+ 0 - 1
zd-modules/zd-algorithm/src/main/java/com/zd/alg/forward/serivce/FireImageService.java

@@ -118,7 +118,6 @@ public class FireImageService {
             return;
         }
         DataPostAnalysisRespDto data = send.getData();
-
         List<AnalysisData> analysisDatas = data.getAnalysisDatas();
         AnalysisData analysisData = analysisDatas.get(0);
         int code = analysisData.getCode();

+ 19 - 15
zd-modules/zd-algorithm/src/main/java/com/zd/alg/forward/utils/HttpUtils.java

@@ -52,15 +52,18 @@ public class HttpUtils {
         return new HttpEntity<>(form, headers);
     }
 
-    public static File multipartFileToFile(MultipartFile file) throws IOException {
-        String originalFilename = file.getOriginalFilename() == null ? "" : file.getOriginalFilename();
-        assert originalFilename!=null;
-        String[] filename = originalFilename.split("\\.");
-        File toFile = File.createTempFile(filename[0], "." + filename[1]);
-        file.transferTo(toFile);
-        //log.info("================>{}",toFile.getAbsoluteFile());
-        //toFile.deleteOnExit();//在jvm 退出时删除
-        return toFile;
+    public static File multipartFileToFile(MultipartFile file) {
+        try {
+            String originalFilename = file.getOriginalFilename() == null ? "" : file.getOriginalFilename();
+            assert originalFilename!=null;
+            String[] filename = originalFilename.split("\\.");
+            File toFile = File.createTempFile(filename[0], "." + filename[1]);
+            file.transferTo(toFile);
+            return toFile;
+        } catch (Exception e) {
+            log.error("【文件转换】 MultipartFile 转 File 异常");
+        }
+        return null;
     }
 
     /**
@@ -129,16 +132,17 @@ public class HttpUtils {
         return null;
     }
 
+    /**
+     * 调用算法服务
+     * @param restTemplate
+     * @param files
+     * @param algorithmYml
+     * @return
+     */
     public static ImgPostResponse<AnalysisReturnData> sendV5(RestTemplate restTemplate, HttpEntity<MultiValueMap<String, Object>> files, AlgorithmYml algorithmYml) {
         ParameterizedTypeReference<ImgPostResponse<AnalysisReturnData>> reference = new ParameterizedTypeReference<ImgPostResponse<AnalysisReturnData>>() {
         };
         ResponseEntity<ImgPostResponse<AnalysisReturnData>> response = restTemplate.exchange(algorithmYml.getImgPostUrl(), HttpMethod.POST, files, reference);
-        if (response.getStatusCode() != HttpStatus.OK) {
-            log.error("算法服务请求异常,请查看算服务器");
-        }
-        if (response.getBody() == null) {
-            log.error("算法服务接口返回异常");
-        }
         return response.getBody();
     }
 }