OCR-上传,校核

This commit is contained in:
liyawei
2022-02-18 14:05:33 +08:00
parent 7e784c280c
commit 86852c92d7
18 changed files with 1241 additions and 1 deletions
+22 -1
View File
@@ -80,7 +80,28 @@
<classifier>jdk15</classifier>
<!-- jdk版本 -->
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk14</artifactId>
<version>1.64</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<!-- thymeleaf依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- pageOffice本地依赖 -->
<dependency>
<groupId>com.zhuozheng</groupId>
<artifactId>pageoffice</artifactId>
<version>4.5.0.9</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/pageoffice4.5.0.9.jar</systemPath>
</dependency>
</dependencies>
</project>
@@ -127,6 +127,9 @@ public class OcrRecordEOController extends JeroController<OcrRecordEO, IOcrRecor
@ApiOperation(value="OCR识别转换记录表-通过id删除", notes="OCR识别转换记录表-通过id删除")
@DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name="id",required=true) String id) {
if (StringUtils.isBlank(id)) {
return Result.error("删除数据不能为空");
}
ocrRecordService.deleteById(id);
return Result.OK("删除成功!");
}
@@ -141,6 +144,9 @@ public class OcrRecordEOController extends JeroController<OcrRecordEO, IOcrRecor
@ApiOperation(value="OCR识别转换记录表-批量删除", notes="OCR识别转换记录表-批量删除")
@DeleteMapping(value = "/deleteBatch")
public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
if (StringUtils.isBlank(ids)) {
return Result.error("删除数据不能为空");
}
this.ocrRecordService.deleteByIds(Arrays.asList(ids.split(",")));
return Result.OK("批量删除成功!");
}
@@ -0,0 +1,168 @@
package com.jero.modules.ocr.controller;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.jero.common.api.vo.Result;
import com.jero.modules.ocr.entity.OcrCallBackResultEO;
import com.jero.modules.ocr.entity.OcrRecordEO;
import com.jero.modules.ocr.service.IOcrRecordEOService;
import com.jero.modules.ocr.service.IOcrRestfulService;
import com.jero.modules.ocr.util.MD5Util;
import com.jero.modules.oss.entity.OSSFile;
import com.jero.modules.oss.service.IOSSFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* @program: OcrDemo
* @description: ocr接口对接类
* @author: duyunbao
* @create: 2019-03-13 18:21
*/
@RestController
@RequestMapping("/ocr/OcrRestful")
@Api(tags="OCR识别")
@Slf4j
public class OcrRestfulController{
@Autowired
private IOcrRestfulService ocrRestfulService;
@Autowired
private IOcrRecordEOService ocrRecordEOService;
@Autowired
private IOSSFileService ossFileService;
//接口回调公钥
@Value("${OCR.publicKey}")
private String OcrPublicKey;
@Value("${OCR.ocrDownPath}")
private String ocrDownPath;
@Value("${jero.path.upload}")
private String filePath;//文件存储路径
/**
* 测试OCR
* @param file
* @return
* @throws Exception
*/
@ApiOperation(value = "请求OCR")
@PostMapping(value="/upload",consumes="multipart/*",headers="content-type=multipart/form-data" )
public Result<?> handleFile(@RequestParam("file") MultipartFile file) throws Exception {
SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
log.info("收到文件上传请求,开始处理文件:【"+sdf.format(new Date())+"");
return ocrRestfulService.handleFile(file,file.getOriginalFilename(),null,"add");
}
/**
* OCR回调
* @param wordFile
* @param jsonFile
* @param ocrCallBackResultEo
* @return
*/
@ApiOperation(value = "OCR回调")
@PostMapping("/OcrHandleResult")
public String OcrHandleResult(@RequestParam("wordFile") MultipartFile wordFile,@RequestParam("jsonFile") MultipartFile jsonFile, OcrCallBackResultEO ocrCallBackResultEo) {
try{
log.info("调取到我了");
log.info("接口回调结果:"+ JSON.toJSONString(ocrCallBackResultEo));
log.info("接口回调时所传文件---wordFile:"+ wordFile.toString() +"; jsonFile:"+jsonFile.toString());
if("error".equals(ocrCallBackResultEo.getResult())){
log.info("客户接口处理文件失败");
ocrRestfulService.updateDb(ocrCallBackResultEo.getTaskID(),"客户接口处理文件失败");
return "{\"result\":\"error\"}";
}
//1.验证 key 是否符合,不符合打回,符合继续
//2.向后传递文件
String key = ocrCallBackResultEo.getKey();
String sign = ocrCallBackResultEo.getTaskID() + OcrPublicKey;
String signMD5 = MD5Util.string2MD5(sign);
// String encpySign =MD5Util.convertMD5(signMD5);
if(!signMD5.equals(key)){
//不同,则认证失败
log.info("认证失败");
ocrRestfulService.updateDb(ocrCallBackResultEo.getTaskID(),"回调接口认证失败");
return "{\"result\":\"Authentication failed\"}";
}
return ocrRestfulService.OcrHandleResult(wordFile,jsonFile,ocrCallBackResultEo.getTaskID());
}catch (Exception e){
log.error(e.getMessage(),e);
return "{\"result\":\"runTimeException\"}";
}
}
/**
* 导入,上传
* @param ocrRecordEO
* @return
* @throws Exception
*/
@ApiOperation(value = "新增OCR内容")
@PostMapping("/addOcrRecord")
public Result<?> addOcrRecord(OcrRecordEO ocrRecordEO) throws Exception {
SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
log.info("收到文件上传请求,开始处理文件:【"+sdf.format(new Date())+"");
// 根据attID查找文件
String fileId = ocrRecordEO.getAttId();
OSSFile ossFile = ossFileService.getById(fileId);
if (ObjectUtil.isNotEmpty(ossFile)) {
String fileOriPath = ossFile.getUrl();
String oriName = ossFile.getFileName();
File pdfFile = new File(fileOriPath);
FileInputStream fileInputStream = new FileInputStream(pdfFile);
MultipartFile multipartFile = new MockMultipartFile(oriName, oriName,
ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
return ocrRestfulService.handleFile(multipartFile,multipartFile.getOriginalFilename(),ocrRecordEO,"add");
} else {
return Result.error("无法找到该文件");
}
}
@ApiOperation(value = "修改OCR内容")
@PutMapping("/updateOcrRecord")
public Result<?> updateOcrRecord(@RequestBody OcrRecordEO ocrRecordEO) throws Exception {
if (StringUtils.isEmpty(ocrRecordEO.getAttId())) {
// ocrRecordEO.setModifyTime(new Date());
ocrRecordEOService.editById(ocrRecordEO);
return Result.OK("保存成功",ocrRecordEO);
} else {
SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
log.info("收到文件上传请求,开始处理文件:【"+sdf.format(new Date())+"");
// 根据attID查找文件
String fileId = ocrRecordEO.getAttId();
OSSFile ossFile = ossFileService.getById(fileId);
if (ObjectUtil.isNotEmpty(ossFile)) {
String fileOriPath = ossFile.getUrl();
String oriName = ossFile.getFileName();
File pdfFile = new File(fileOriPath);
FileInputStream fileInputStream = new FileInputStream(pdfFile);
MultipartFile multipartFile = new MockMultipartFile(oriName, oriName,
ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
return ocrRestfulService.handleFile(multipartFile,multipartFile.getOriginalFilename(),ocrRecordEO,"update");
} else {
return Result.error("无法找到该文件");
}
}
}
}
@@ -0,0 +1,82 @@
package com.jero.modules.ocr.controller;
import com.jero.common.aspect.annotation.AutoLog;
import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* @Description:
* @Author: yangxuenan
* date: 2019/12/30 10:53
*/
@RestController
@RequestMapping("/ocr/pageOffice")
@Api(tags="pageoffice接口")
@Slf4j
public class PageOfficeController {
@AutoLog(value = "pageoffice-主页")
@ApiOperation(value="pageoffice-主页", notes="pageoffice-主页")
@RequestMapping(value="/index", method= RequestMethod.GET)
public ModelAndView showIndex(){
ModelAndView mv = new ModelAndView("index");
return mv;
}
/**
* office online打开
*
* @param request
* @param map
* @return
*/
@AutoLog(value = "pageoffice-在线编辑")
@ApiOperation(value="pageoffice-在线编辑", notes="pageoffice-在线编辑")
@RequestMapping(value="/word", method=RequestMethod.GET)
public ModelAndView showWord(HttpServletRequest request, Map<String,Object> map){
//--- PageOffice的调用代码 开始 -----
PageOfficeCtrl poCtrl=new PageOfficeCtrl(request);
poCtrl.setServerPage("/poserver.zz");//设置授权程序servlet
poCtrl.addCustomToolButton("保存","Save()",1); //添加自定义按钮
poCtrl.addCustomToolButton("打印", "PrintFile()", 6);
poCtrl.addCustomToolButton("全屏/还原", "IsFullScreen()", 4);
poCtrl.addCustomToolButton("关闭", "CloseFile()", 21);
poCtrl.setSaveFilePage("/save");//设置保存的action
poCtrl.webOpen("D:\\test.docx", OpenModeType.docAdmin,"张三");
poCtrl.setCaption("信息平台");
map.put("pageoffice",poCtrl.getHtmlCode("PageOfficeCtrl1"));
//--- PageOffice的调用代码 结束 -----
ModelAndView mv = new ModelAndView("word");
return mv;
}
/**
* 保存office
*
* @param request
* @param response
*/
@RequestMapping("/save")
public void saveFile(HttpServletRequest request, HttpServletResponse response){
FileSaver fs = new FileSaver(request, response);
//保存文件
fs.saveToFile("D:\\test.docx");
fs.close();
}
}
@@ -0,0 +1,38 @@
package com.jero.modules.ocr.entity;
/**
* @program: OcrDemo
* @description: orc调取回调函数的参数
* @author: duyunbao
* @create: 2019-03-13 16:14
*/
public class OcrCallBackResultEO {
private String result ;
private String taskID ;
private String key;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getTaskID() {
return taskID;
}
public void setTaskID(String taskID) {
this.taskID = taskID;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
@@ -0,0 +1,83 @@
package com.jero.modules.ocr.entity;
/**
* @program: OcrDemo
* @description: ocr接口请求实体类
* @author: duyunbao
* @create: 2019-03-13 20:46
*/
public class OcrRequestEO {
private String userId;
private String authCode;
private String convertType;
private String Filename;
private String taskId;
private String callBackUrl;
private String callBackMethod;
private String fileContent;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getAuthCode() {
return authCode;
}
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
public String getConvertType() {
return convertType;
}
public void setConvertType(String convertType) {
this.convertType = convertType;
}
public String getFilename() {
return Filename;
}
public void setFilename(String filename) {
Filename = filename;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getCallBackUrl() {
return callBackUrl;
}
public void setCallBackUrl(String callBackUrl) {
this.callBackUrl = callBackUrl;
}
public String getCallBackMethod() {
return callBackMethod;
}
public void setCallBackMethod(String callBackMethod) {
this.callBackMethod = callBackMethod;
}
public String getFileContent() {
return fileContent;
}
public void setFileContent(String fileContent) {
this.fileContent = fileContent;
}
}
@@ -0,0 +1,30 @@
package com.jero.modules.ocr.entity;
/**
* @program: OcrDemo
* @description: ocr返回结果
* @author: duyunbao
* @create: 2019-03-13 15:35
*/
public class OcrResultEO {
private String resultCode;
private String returnMessage;
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getReturnMessage() {
return returnMessage;
}
public void setReturnMessage(String returnMessage) {
this.returnMessage = returnMessage;
}
}
@@ -0,0 +1,23 @@
package com.jero.modules.ocr.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.jero.common.api.vo.Result;
import com.jero.modules.ocr.entity.OcrRecordEO;
import org.springframework.web.multipart.MultipartFile;
/**
* @Author: liyawei
* @Description:
* @Date: Created in 16:19 2022/2/16
*/
public interface IOcrRestfulService{
Result<?> handleFile(MultipartFile file, String fileName, OcrRecordEO getOcrEO, String type) throws Exception;
String OcrHandleResult(MultipartFile wordFile,MultipartFile jsonFile,String taskId) throws Exception;
OcrRecordEO getOcrResult(String taskId, int i) throws Exception;
void updateDb(String taskId,String result) throws Exception;
boolean checkFileName(String fileName);
}
@@ -53,6 +53,7 @@ public class OcrRecordEOServiceImpl extends ServiceImpl<OcrRecordEOMapper, OcrRe
*/
@Override
public void deleteById(String id) {
//TODO 删除对应的本地文件
removeById(id);
}
@@ -64,6 +65,7 @@ public class OcrRecordEOServiceImpl extends ServiceImpl<OcrRecordEOMapper, OcrRe
*/
@Override
public void deleteByIds(List<String> ids) {
//TODO 删除对应的本地文件
removeByIds(ids);
}
@@ -0,0 +1,246 @@
package com.jero.modules.ocr.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.jero.common.api.vo.Result;
import com.jero.common.system.vo.LoginUser;
import com.jero.modules.ocr.entity.OcrRecordEO;
import com.jero.modules.ocr.entity.OcrResultEO;
import com.jero.modules.ocr.service.IOcrRecordEOService;
import com.jero.modules.ocr.service.IOcrRestfulService;
import com.jero.modules.ocr.util.Base64Util;
import com.jero.modules.ocr.util.RsaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* @program: OcrDemo
* @description: ocr识别转换
* @author: duyunbao
* @create: 2019-03-13 14:06
*/
@Service
@Transactional(value = "transactionManager", readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
@Slf4j
public class OcrRestfulServiceImpl implements IOcrRestfulService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private IOcrRecordEOService ocrRecordEOService;
//请求处理文件url
@Value("${OCR.handleFileUrl}")
private String RestHandleFileUrl;
//请求处理usrid
@Value("${OCR.userId}")
private String OcrUserId;
//请求处理客户认证码
@Value("${OCR.authCode}")
private String OcrAuthCode;
//接口回调url
@Value("${OCR.callBackUrl}")
private String RestCallBackUrl;
//ocr处理文件后存放url
@Value("${OCR.ocrPath}")
private String ocrFilePath;
@Value("${OCR.ocrDownPath}")
private String ocrDownPath;
@Value("${OCR.times}")
private Integer ocrTimes;
@Value("${OCR.convertType}")
private String convertType;
public Result<?> handleFile(MultipartFile file, String fileName, OcrRecordEO getOcrEO, String type) throws Exception {
String taskId = "";
if ("add".equals(type)) {
taskId = UUID.randomUUID().toString().replace("-", "");
} else {
taskId = getOcrEO.getId();
}
String authCode = RsaUtil.publicEncrypt(OcrAuthCode);
if(authCode == null){
log.error("客户认证RSA加密失败");
return Result.error("客户认证RSA加密失败");
}
String fileContent = Base64Util.PDFToBase64(file);
if(fileContent == null){
log.error("PDF转Base64失败");
return Result.error("PDF转Base64失败");
}
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add("userId",OcrUserId);
paramMap.add("authCode",authCode);
paramMap.add("convertType",convertType);
paramMap.add("fileName",fileName);
paramMap.add("fileContent",fileContent);
paramMap.add("taskId",taskId);
paramMap.add("callBackUrl",RestCallBackUrl);
paramMap.add("callBackMethod","");
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
log.info("处理完文件数据,开始请求OCR接口数据:【"+sdf.format(new Date())+"");
try{
ResponseEntity<String> responseEntity = restTemplate.postForEntity(RestHandleFileUrl, httpEntity, String.class);
log.info("请求OCR接口完毕,返回响应状态:【"+sdf.format(new Date())+"");
HttpStatus statusCode = responseEntity.getStatusCode();
if(statusCode != HttpStatus.OK){
log.error("请求出现异常:"+statusCode.value());
return Result.error("请求出现异常");
}else{
OcrResultEO ocrResultEO = JSONObject.parseObject(responseEntity.getBody(), OcrResultEO.class);
if(ocrResultEO.getResultCode().equals("0")){
if ("add".equals(type)) {
OcrRecordEO ocrRecordEO = new OcrRecordEO();
ocrRecordEO.setId(taskId);
ocrRecordEO.setFileName(fileName);
ocrRecordEO.setResultContent("转换中");
ocrRecordEO.setStandNumber(getOcrEO.getStandNumber());
ocrRecordEO.setStandName(getOcrEO.getStandName());
ocrRecordEO.setFileType(getOcrEO.getFileType());
// LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
// ocrRecordEO.setCreateBy(sysUser.getId());
// ocrRecordEO.setCreateTime(new Date());
ocrRecordEOService.add(ocrRecordEO);
return Result.OK("加入转换成功", taskId);
} else {
OcrRecordEO ocrRecordEO = new OcrRecordEO();
ocrRecordEO.setId(taskId);
ocrRecordEO.setFileName(fileName);
ocrRecordEO.setResultContent("转换中");
ocrRecordEO.setStandNumber(getOcrEO.getStandNumber());
ocrRecordEO.setStandName(getOcrEO.getStandName());
ocrRecordEO.setFileType(getOcrEO.getFileType());
ocrRecordEO.setCreateTime(new Date());
ocrRecordEOService.editById(ocrRecordEO); //TODO ??
return Result.OK( "加入转换成功", taskId);
}
}else{
return Result.error(ocrResultEO.getReturnMessage());
}
}
}catch (Exception e){
log.error(e.getMessage(),e);
return Result.error("OCR接口请求出现异常,无法将文件传输到OCR引擎!");
}
}
public String OcrHandleResult(MultipartFile wordFile,MultipartFile jsonFile,String taskId) throws Exception {
//首先将文件保存至本地
String saveWordFilePath=null;
String saveWordFileName=null;
if(wordFile!=null && !wordFile.isEmpty()){
saveWordFileName= UUID.randomUUID().toString().replace("-", "") + "_"+wordFile.getOriginalFilename();
saveWordFilePath=ocrFilePath+saveWordFileName;
FileUtils.copyInputStreamToFile(wordFile.getInputStream(),new File(saveWordFilePath));
}
String saveJsonFilePath=null;
String saveJsonFileName=null;
if(jsonFile!=null && !jsonFile.isEmpty()){
saveJsonFileName=UUID.randomUUID().toString().replace("-", "") + "_"+jsonFile.getOriginalFilename();
saveJsonFilePath=ocrFilePath+saveJsonFileName;
FileUtils.copyInputStreamToFile(jsonFile.getInputStream(),new File(saveJsonFilePath));
}
//开始将文件保存至数据库中
if(StringUtils.isNotEmpty(saveWordFilePath) && StringUtils.isNotEmpty(saveJsonFilePath)){
OcrRecordEO ocrRecordEO = new OcrRecordEO();
ocrRecordEO.setId(taskId);
ocrRecordEO.setDocName(saveWordFilePath);
ocrRecordEO.setJsonName(saveJsonFilePath);
ocrRecordEO.setDocRealName(saveWordFileName);
ocrRecordEO.setWordFileCode(null);
ocrRecordEO.setJsonRealName(saveJsonFileName);
ocrRecordEO.setJsonFileCode(null);
ocrRecordEO.setUpdateTime(new Date());
ocrRecordEO.setResultContent("转换成功");
ocrRecordEOService.editById(ocrRecordEO);
return "{\"result\":\"success\"}";
}else{
updateDb(taskId,"error:File does not exist");
return "{\"result\":\"error:File does not exist\"}";//文件不存在
}
}
public OcrRecordEO getOcrResult(String taskId, int i) throws Exception {
log.info("开始获取转换结果-------------------------");
OcrRecordEO ocrRecordEO = ocrRecordEOService.getById(taskId);
if(ocrRecordEO == null || StringUtils.isEmpty(ocrRecordEO.getDocRealName())){
i++;
if(i<ocrTimes) {
log.info("转换结果为空,等待 10秒继续获取-------------------------");
Thread.sleep(10000);
getOcrResult(taskId,i);
}else {
log.info("获取转换结果超时-------------------------");
return null;
}
}else {
log.info("获取转换结果成功-------------------------");
ocrRecordEO.setDocRealFile(ocrDownPath+ocrRecordEO.getDocRealName());
ocrRecordEO.setJsonRealFile(ocrDownPath+ocrRecordEO.getJsonRealName());
return ocrRecordEO;
}
return null;
}
public void updateDb(String taskId,String result) throws Exception {
OcrRecordEO ocrRecordEO = new OcrRecordEO();
ocrRecordEO.setId(taskId);
ocrRecordEO.setUpdateTime(new Date());
ocrRecordEO.setResultContent(result);
ocrRecordEOService.editById(ocrRecordEO);
}
public boolean checkFileName(String fileName){
String file1="GB 1589-2016 汽车、挂车及汽车列车外廓尺寸、轴荷及质量限值.pdf";
String file2="GB 7258-2017 机动车运行安全技术条件.pdf";
String file3="GB 11551-2014 汽车正面碰撞的乘员保护.pdf";
String file4="GBT 19753-2013 轻型混合动力电动汽车能量消耗量试验方法.pdf";
// String file5="WST 292-2008 救护车.docx";
if(StringUtils.equals(fileName,file1)){
return true;
}
if(StringUtils.equals(fileName,file2)){
return true;
}
if(StringUtils.equals(fileName,file3)){
return true;
}
if(StringUtils.equals(fileName,file4)){
return true;
}
return false;
}
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,77 @@
package com.jero.modules.ocr.util;
import java.security.MessageDigest;
/**
* 采用MD5加密解密
* @author tfq
* @datetime 2011-10-13
*/
public class MD5Util {
/***
* MD5加码 生成32位md5码
*/
public static String string2MD5(String inStr){
MessageDigest md5 = null;
try{
md5 = MessageDigest.getInstance("MD5");
}catch (Exception e){
System.out.println(e.toString());
e.printStackTrace();
return "";
}
char[] charArray = inStr.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++){
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 加密解密算法 执行一次加密,两次解密
*/
public static String convertMD5(String inStr){
char[] a = inStr.toCharArray();
for (int i = 0; i < a.length; i++){
a[i] = (char) (a[i] ^ 't');
}
String s = new String(a);
return s;
}
// 测试主函数
public static void main(String args[]) {
/* String s = new String("tangfuqiang");
System.out.println("原始:" + s);
System.out.println("MD5后:" + string2MD5(s));
System.out.println("加密的:" + convertMD5(s));
System.out.println("解密的:" + convertMD5(convertMD5(s)));*/
// String fileId = "ATT_FILE_07_JLBUTUSFXDRUKTVX5BT5";
// String key = "dufy20170329java";
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH");
// String time = df.format(new Date());
// String sign = fileId + time + key;
String str="GVJ3EZKW6NTK6Z5U92QE"+"EC4KKA6ZDTCPAOCRBC5M";
String key="ecd2c0791b398882310c4edcc1eee42b";
String entoryStr = string2MD5(str);
System.out.println(entoryStr);
System.out.println(key);
}
}
@@ -0,0 +1,129 @@
package com.jero.modules.ocr.util;
import org.apache.poi.util.IOUtils;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
import org.bouncycastle.util.encoders.Base64;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
/**
* @program: OcrDemo
* @description: rsa加密解密
* @author: duyunbao
* @create: 2019-03-14 19:54
*/
public class RsaUtil {
private static final Logger logger = LoggerFactory.getLogger(RsaUtil.class);
public static final String CHARSET = "UTF-8";
public static final String RSA_ALGORITHM = "RSA";
/// RSA公钥格式转换,.net->java
public static String RSAPublicKeyDotNet2Java() throws IOException, DocumentException {
/* SAXReader reader = new SAXReader();
Document document = reader.read(new File("../../../resources/rsa/publicRSAXML.xml"));
Element root = document.getRootElement();
Element ModulusElem = root.element("Modulus");
Element ExponentElem = root.element("Exponent");
BigInteger m = new BigInteger(1, Base64.decode(ModulusElem.elements().get(0).getData().toString()));
BigInteger p = new BigInteger(1, Base64.decode(ExponentElem.elements().get(0).getData().toString()));*/
BigInteger m = new BigInteger(1, Base64.decode("ncJeLmq4CT6t07x1Ct8LJn8/h6vPaSoySEcirRxAfFS7uoxxaWTyQE3khA4idvwky2ZrLtZjqVCFWRlHADKB5OCbRsVxvQv7kAR3VASJnCUtXH1lm+5zF9vxcw20ISfqEYUwikMDDogbVyLzNjwU/7ZfzzNY5lG+KsZxV8tuOE8="));
BigInteger p = new BigInteger(1, Base64.decode("AQAB"));
RSAKeyParameters pub = new RSAKeyParameters(false, m, p);
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(pub);
byte[] serializedPublicBytes = publicKeyInfo.toASN1Primitive().getEncoded();
return Base64.toBase64String(serializedPublicBytes);
}
/**
}
* 得到公钥
* @param publicKey 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
// 通过X509编码的Key指令获得公钥对象
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decode(publicKey));
RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
return key;
}
/**
* 公钥加密
* @param data
* @return
*/
public static String publicEncrypt(String data) {
RSAPublicKey publicKey = null;
try {
publicKey = getPublicKey(RSAPublicKeyDotNet2Java());
}catch (Exception e){
logger.error(e.getMessage(),e);
return null;
}
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.toBase64String(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET),
publicKey.getModulus().bitLength()));
} catch (Exception e) {
logger.error("加密字符串[" + data + "]时遇到异常",e);
return null;
}
}
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
int maxBlock = 0;
if (opmode == Cipher.DECRYPT_MODE) {
maxBlock = keySize / 8;
} else {
maxBlock = keySize / 8 - 11;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] buff;
int i = 0;
try {
while (datas.length > offSet) {
if (datas.length - offSet > maxBlock) {
buff = cipher.doFinal(datas, offSet, maxBlock);
} else {
buff = cipher.doFinal(datas, offSet, datas.length - offSet);
}
out.write(buff, 0, buff.length);
i++;
offSet = i * maxBlock;
}
} catch (Exception e) {
logger.error("加解密阀值为[" + maxBlock + "]的数据时发生异常",e);
}
byte[] resultDatas = out.toByteArray();
IOUtils.closeQuietly(out);
return resultDatas;
}
}
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- office插件js begin 必须引入-->
<script type="text/javascript" src="./jquery.min.js"></script>
<script type="text/javascript" src="./pageoffice.js" id="po_js_main"></script>
</head>
<body>
<a href="javascript:POBrowser.openWindowModeless('/api/lawss/pageOffice/word','width=1200px;height=800px;');">打开文件</a>
</body>
</html>
@@ -0,0 +1,70 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input id="Button1" type="button" value="隐藏/显示 标题栏" οnclick="return Button1_onclick()" />
<input id="Button2" type="button" value="隐藏/显示 菜单栏" οnclick="return Button2_onclick()" />
<input id="Button3" type="button" value="隐藏/显示 自定义工具栏" οnclick="return Button3_onclick()" />
<input id="Button4" type="button" value="隐藏/显示 Office工具栏" οnclick="return Button4_onclick()" />
<div style="width:1000px;height:700px;" th:utext="${pageoffice}"> </div>
<script type="text/javascript">
function Save() {
document.getElementById("PageOfficeCtrl1").WebSave();
}
function PrintFile(){
document.getElementById("PageOfficeCtrl1").ShowDialog(4);
}
function IsFullScreen(){
document.getElementById("PageOfficeCtrl1").FullScreen = !document.getElementById("PageOfficeCtrl1").FullScreen;
}
function CloseFile(){
window.external.close();
}
function BeforeBrowserClosed(){
if (document.getElementById("PageOfficeCtrl1").IsDirty){
if(confirm("提示:文档已被修改,是否继续关闭放弃保存 ?"))
{
return true;
}else{
return false;
}
}
}
// 隐藏/显示 标题栏
function Button1_onclick() {
var bVisible = document.getElementById("PageOfficeCtrl1").Titlebar;
document.getElementById("PageOfficeCtrl1").Titlebar = !bVisible;
}
// 隐藏/显示 菜单栏
function Button2_onclick() {
var bVisible = document.getElementById("PageOfficeCtrl1").Menubar;
document.getElementById("PageOfficeCtrl1").Menubar = !bVisible;
}
// 隐藏/显示 自定义工具栏
function Button3_onclick() {
var bVisible = document.getElementById("PageOfficeCtrl1").CustomToolbar;
document.getElementById("PageOfficeCtrl1").CustomToolbar = !bVisible;
}
// 隐藏/显示 Office工具栏
function Button4_onclick() {
var bVisible = document.getElementById("PageOfficeCtrl1").OfficeToolbars;
document.getElementById("PageOfficeCtrl1").OfficeToolbars = !bVisible;
}
</script>
</body>
</html>
@@ -0,0 +1,29 @@
package com.jero.modules.oss.test;
import com.jero.LawNioApplication;
import com.jero.modules.oss.entity.OSSFile;
import com.jero.modules.oss.service.IOSSFileService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @Author: liyawei
* @Description:
* @Date: Created in 13:49 2022/2/17
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = LawNioApplication.class)
public class OCRTest {
@Autowired
private IOSSFileService ossFileService;
@Test
public void testOssFileDelete() {
OSSFile file = ossFileService.getById("92931b26153e986c3335adfb465dbc5e");
boolean ok = ossFileService.delete(file);
System.out.println(ok);
}
}
+12
View File
@@ -136,6 +136,18 @@
<version>${jero.version}</version>
</dependency>
<dependency>
<groupId>com.jero.boot</groupId>
<artifactId>jero-boot-modules</artifactId>
<version>${jero.version}</version>
<exclusions>
<exclusion>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk14</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- jeecg tools -->
<dependency>
<groupId>com.jero.boot</groupId>