diff --git a/adc-da-activiti/src/main/java/com/adc/da/common/ActDefineStartMap.java b/adc-da-activiti/src/main/java/com/adc/da/common/ActDefineStartMap.java index dc39c227..2fa07426 100644 --- a/adc-da-activiti/src/main/java/com/adc/da/common/ActDefineStartMap.java +++ b/adc-da-activiti/src/main/java/com/adc/da/common/ActDefineStartMap.java @@ -32,6 +32,9 @@ public class ActDefineStartMap { map.put("laws2","PolicyCommentProcessWorkFlow"); map.put("laws3","KCSTPReviewProcessWorkFlow"); + // 企标制修订流程及企业标准库流程 + map.put("buss1","bussLibraryWkflow"); + //张超然 map.put("20","StandardApplyMeetProcess"); map.put("21","StandardMeetProcess"); diff --git a/adc-da-convert/src/main/java/com/adc/da/convert/mq/SendUploadConvertService.java b/adc-da-convert/src/main/java/com/adc/da/convert/mq/SendUploadConvertService.java new file mode 100644 index 00000000..7a7b42e0 --- /dev/null +++ b/adc-da-convert/src/main/java/com/adc/da/convert/mq/SendUploadConvertService.java @@ -0,0 +1,368 @@ +//package com.adc.da.convert.mq; +// +//import com.adc.da.att.entity.AttFileEO; +//import com.adc.da.att.service.IAttFileEOService; +//import com.adc.da.common.SarTypeEnum; +//import com.adc.da.common.UseModuleEnum; +//import com.adc.da.convert.common.AsposeOfficeConvertUtils; +//import com.adc.da.mq.CreateMQService; +//import com.adc.da.slrs.otConvertMq.entity.OtConvertMq; +//import com.adc.da.slrs.otConvertMq.service.IOtConvertMqService; +//import com.adc.da.slrs.sarBussStandFile.dao.SarBussStandFileDao; +//import com.adc.da.slrs.sarBussStandFile.entity.SarBussStandFile; +//import com.adc.da.slrs.sarLawsFile.dao.SarLawsFileDao; +//import com.adc.da.slrs.sarLawsFile.entity.SarLawsFile; +//import com.adc.da.slrs.sarStandFile.dao.SarStandFileDao; +//import com.adc.da.slrs.sarStandFile.entity.SarStandFile; +//import com.adc.da.sys.util.LoginUserUtil; +//import com.adc.da.util.http.ResponseMessage; +//import com.adc.da.util.http.Result; +//import com.adc.da.util.utils.StringUtils; +//import com.adc.da.util.utils.UUID; +//import com.rabbitmq.client.Channel; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +//import org.springframework.amqp.rabbit.annotation.Exchange; +//import org.springframework.amqp.rabbit.annotation.Queue; +//import org.springframework.amqp.rabbit.annotation.QueueBinding; +//import org.springframework.amqp.rabbit.annotation.RabbitListener; +//import org.springframework.amqp.support.AmqpHeaders; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.beans.factory.annotation.Value; +//import org.springframework.messaging.Message; +//import org.springframework.stereotype.Component; +// +//import java.io.File; +//import java.util.Date; +//import java.util.Map; +// +//@Component +//public class SendUploadConvertService { +// +// // 文档转换远程服务IP地址s +// @Value("${convert.host}") +// private String convertHost; +// +// @Value("${server.port}") +// private String port; +// +// @Value("${file.path}") +// private String localFilePath; +// +// @Autowired +// private IAttFileEOService attFileEOService; +// +// @Autowired +// private CreateMQService convertMq; +// +// @Autowired +// private IOtConvertMqService convertMqEOService; +// +// @Autowired +// private SarStandFileDao sarStandFileEODao; +// +// @Autowired +// private SarBussStandFileDao sarBussStandFileEODao; +// +// @Autowired +// private SarLawsFileDao sarLawsFileDao; +// +// private static final Logger logger = LoggerFactory.getLogger(SendUploadConvertService.class); +// +// @RabbitListener(bindings = @QueueBinding( +// value = @Queue(value = "createUploadConvertMQ_SQ_GSAR_RELEASE", durable = "true"), +// exchange = @Exchange(value = "convertUpload-exchange_SQ_GSAR_RELEASE", ignoreDeclarationExceptions = "true"), +// key = "convertUpload-key_SQ_GSAR_RELEASE")) +// public void createMQ(Map convertInfo, Message message, Channel channel) throws Exception{ +// try{ +// try{ +// Thread.sleep(5000); +// insertConvertMsg(convertInfo); +// }catch(InterruptedException e){ +// logger.error(e.toString()); +// Thread.currentThread().interrupt(); +// } +// } catch (Exception e) { +// logger.error("文档转换消息队列进入添加数据方法前失败!"); +// logger.error(e.getMessage(),e); +// }finally { +// Long tag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG); +// channel.basicAck(tag,false); +// } +// +// } +// +// public void insertConvertMsg(Map convertInfo) throws Exception{ +// docUploadConvert(convertMqEO); +// } +// +// /** +// * @Description 文件转换 +// * Date 2018/8/21 15:51 +// * @Param [path] +// * @return com.adc.da.util.http.ResponseMessage +// **/ +// public ResponseMessage docUploadConvert(OtConvertMq convertMqEO) throws Exception{ +// //保存在数据库中的ID +// String path = localFilePath + convertMqEO.getFilePath(); +// path = path.replace("//","/"); +// String convertId = convertMqEO.getId(); +// try { +// //进入转换方法中,修改OT_CONVERT表中状态为转换中 +// convertMqEO.setId(convertId); +// convertMqEO.setModifyTime(new Date()); +// convertMqEO.setMqState(3); +// convertMqEOService.updateById(convertMqEO); +// //开始转换。。。。。。 +// if(!"".equals(path)){ +// String converfilename = path.replaceAll("\\\\", "/"); +// logger.info("*****上传路径:*******"+localFilePath); +// logger.info("************文件路径:**********" + convertMqEO.getFilePath()); +//// logger.info("************接口:**********" + port); +// logger.info("*****上传路径替换,加入文件名*******"+converfilename); +// //截取文件类型 +// int index = converfilename.lastIndexOf("."); +// String fileType = converfilename.substring(index,converfilename.length()); +// String fileOriName = converfilename.substring(0,index); +//// //调用转换类DocConverter,并将需要转换的文件传递给该类的构造方法 +//// DocConverterPdf d = new DocConverterPdf(converfilename,fileType); +//// d.setConvertHost(convertHost); +//// //调用conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf; +//// File getPdf = d.conver(fileType); +//// //调用getswfPath()方法,打印转换后的swf文件路径 +//// String dPath = d.getpdfPath(); +// String savePdfFileName = converfilename.substring(0, converfilename.lastIndexOf(".")); +// String savePdfPath = savePdfFileName+".pdf"; +// AsposeOfficeConvertUtils.convertOfficeFileToPDF(fileType,converfilename,savePdfPath); +// File pdfFile = new File(savePdfPath); +// logger.info("*****转换后的pdf文件路径*******"+savePdfPath); +// //判断是否转换成功,修改数据状态 +// if(!savePdfPath.isEmpty() && pdfFile.length()>0){ +// // 上传转换后文件 +// String pdfId = attFileEOService.saveFileAttId(pdfFile); +// logger.info("////////转换后文件id"+pdfId); +// int count = 0; +// if("0".equals(convertMqEO.getAddOrUp())){ +// count = insertConvertDocToFiles(convertMqEO,pdfId,fileOriName,fileType); +// } else { +// //查询之前在资源与文件关联表中是否有转换成功的数据,如果有执行修改,没有执行新增 +// if(StringUtils.isNotEmpty(convertMqEO.getPdfId())){ +// count = updateConvertDocToFIles(convertMqEO,pdfId); +// } else { +// count = insertConvertDocToFiles(convertMqEO,pdfId,fileOriName,fileType); +// } +// } +// convertMqEO.setId(convertId); +// if (count>0) { +// // 转换成功 +// convertMqEO.setModifyTime(new Date()); +// convertMqEO.setMqState(1); +// convertMqEOService.updateById(convertMqEO); +// } else { +// // 转换失败 +// convertMqEO.setModifyTime(new Date()); +// convertMqEO.setMqState(2); +// convertMqEOService.updateById(convertMqEO); +// } +// } else { +// // 转换失败 +// convertMqEO.setId(convertId); +// convertMqEO.setModifyTime(new Date()); +// convertMqEO.setMqState(2); +// convertMqEOService.updateById(convertMqEO); +//// if(convertMqEO.getAgainNum()<=5){ +//// throw new Exception("转换失败"); +//// } +// } +// return Result.success(savePdfPath); +// } else { +// logger.error("转换时未获取到文件路径!"); +// return Result.error("文件存储失败,请重试"); +// } +// } catch (Exception e) { +// // 转换失败 +// logger.error("转换过程中失败!"); +// logger.error(e.getMessage(),e); +// convertMqEO.setId(convertId); +// convertMqEO.setMqState(2); +// convertMqEOService.updateById(convertMqEO); +//// this.restartUploadConvert(convertMqEO); +// return Result.error("r0072", "文件转换失败,请重试"); +// } +// } +// +// public ResponseMessage restartUploadConvert(OtConvertMq convertInfo) throws Exception{ +// OtConvertMq convertMqEO = new OtConvertMq(); +// convertMqEO.setLawsId(convertInfo.getLawsId()); +// convertMqEO.setConvertType(convertInfo.getConvertType()); +// convertMqEO.setAttId(convertInfo.getAttId()); +// convertMqEO.setOriAttId(convertInfo.getOriAttId()); +// convertMqEO.setId(convertInfo.getId()); +// convertMqEO.setFilePath(convertInfo.getFilePath()); +// convertMqEO.setAddOrUp(convertInfo.getAddOrUp()); +// convertMqEO.setPdfId(convertInfo.getPdfId()); +// convertMqEO.setStandFileClassify(convertInfo.getStandFileClassify()); +// int countAdd = 0; +// convertMqEO.setAddOrUp("1"); +// int againNumNew = Integer.valueOf(convertInfo.getAgainNum()); +// convertMqEO.setAgainNum(againNumNew+1); +// convertMq.sendMQ(convertMqEO); +// return Result.success("true","已重新加入转换",""); +// +// } +// +// /** +// * @Author yangxuenan +// * @Description 修改标准法规文件表pdf信息 +// * Date 2018/10/31 17:09 +// * @Param [convertMq, pdfId] +// * @return int +// **/ +// public int updateConvertDocToFIles(OtConvertMq convertMq,String pdfId){ +// int countSuccess = 0; +// if(SarTypeEnum.STAND.getValue().equals(convertMq.getConvertType())){ +// SarStandFile lawsFile = new SarStandFile(); +// lawsFile.setId(convertMq.getPdfId()); +// lawsFile.setAttId(pdfId); +// lawsFile.setOriAttId(convertMq.getOriAttId()); +// lawsFile.setModifyTime(new Date()); +// lawsFile.setUseModel(UseModuleEnum.WEB_FILE.getValue()); +// countSuccess = sarStandFileEODao.updateByPrimaryKeySelective(lawsFile); +// } else if (SarTypeEnum.LAWS_STAND.getValue().equals(convertMq.getConvertType())) { +// SarLawsFile lawsFile = new SarLawsFile(); +// lawsFile.setId(convertMq.getPdfId()); +// lawsFile.setAttId(pdfId); +// lawsFile.setOriAttId(convertMq.getOriAttId()); +// lawsFile.setUseModel(UseModuleEnum.WEB_FILE.getValue()); +// lawsFile.setModifyTime(new Date()); +// countSuccess = sarLawsFileDao.updateByPrimaryKeySelective(lawsFile); +// } else if (SarTypeEnum.BUSINESS.getValue().equals(convertMq.getConvertType())) { +// SarBussStandFile lawsFile = new SarBussStandFile(); +// lawsFile.setId(convertMq.getPdfId()); +// lawsFile.setAttId(pdfId); +// lawsFile.setOriAttId(convertMq.getOriAttId()); +// lawsFile.setUseModule(UseModuleEnum.WEB_FILE.getValue()); +// lawsFile.setModifyTime(new Date()); +// countSuccess = sarBussStandFileEODao.updateByPrimaryKeySelective(lawsFile); +// }else if (SarTypeEnum.RECORDS.getValue().equals(convertMq.getConvertType())) { +//// SarBussRecordsFileEO lawsFile = new SarBussRecordsFileEO(); +//// lawsFile.setId(convertMq.getPdfId()); +//// lawsFile.setRecordsId(convertMq.getLawsId()); +//// lawsFile.setAttId(pdfId); +//// lawsFile.setOriAttId(convertMq.getOriAttId()); +//// lawsFile.setUseModel(UseModuleEnum.WEB_FILE.getValue()); +//// lawsFile.setValidFlag("0"); +//// lawsFile.setCreationTime(new Date()); +//// lawsFile.setModifyTime(new Date()); +//// countSuccess = sarBussRecordsFileEODao.updateByPrimaryKeySelective(lawsFile); +// } +// else { +//// SarFileSplitItemsFileEO lawsFile = new SarFileSplitItemsFileEO(); +//// lawsFile.setId(convertMq.getPdfId()); +//// lawsFile.setAttId(pdfId); +////// lawsFile.setOriAttId(convertMq.getOriAttId()); +//// lawsFile.setUseModel(UseModuleEnum.WEB_FILE.getValue()); +//// lawsFile.setModifyTime(new Date()); +//// countSuccess = sarFileSplitItemsFileEODao.updateByPrimaryKeySelective(lawsFile); +// } +// return countSuccess; +// } +// +// /** +// * @Author yangxuenan +// * @Description 添加标准法规文件表pdf信息 +// * Date 2018/10/30 21:52 +// * @Param [convertMq] +// * @return int +// **/ +// public int insertConvertDocToFiles(OtConvertMq convertMq,String pdfId,String fileOriName,String fileType) { +// int countSuccess = 0; +// String creationUser = LoginUserUtil.getUserId(); +// if(SarTypeEnum.STAND.getValue().equals(convertMq.getConvertType())){ +// SarStandFile lawsFile = new SarStandFile(); +// lawsFile.setId(UUID.randomUUID(20)); +// lawsFile.setStandId(convertMq.getLawsId()); +//// lawsFile.setResId(convertMq.getResId()); +// lawsFile.setAttId(pdfId); +// lawsFile.setOriAttId(convertMq.getOriAttId()); +// lawsFile.setValidFlag("0"); +// lawsFile.setCreationUser(creationUser); +// lawsFile.setCreationTime(new Date()); +// lawsFile.setModifyTime(new Date()); +// lawsFile.setUseModel(UseModuleEnum.WEB_FILE.getValue()); +// lawsFile.setStandFileClassify(convertMq.getStandFileClassify()); +// lawsFile.setFileName(fileOriName+".pdf"); +// lawsFile.setFileSuffix("pdf"); +// countSuccess = sarStandFileEODao.insertSelective(lawsFile); +// } else if (SarTypeEnum.LAWS_STAND.getValue().equals(convertMq.getConvertType())) { +// SarLawsFile lawsFile = new SarLawsFile(); +// lawsFile.setId(UUID.randomUUID(20)); +// lawsFile.setLawsId(convertMq.getLawsId()); +// lawsFile.setResId(convertMq.getResId()); +// lawsFile.setAttId(pdfId); +// lawsFile.setOriAttId(convertMq.getOriAttId()); +// lawsFile.setUseModel(UseModuleEnum.WEB_FILE.getValue()); +// lawsFile.setValidFlag(0); +// lawsFile.setCreationTime(new Date()); +// lawsFile.setModifyTime(new Date()); +// lawsFile.setLawsFileClassify(convertMq.getLawsFileClassify()); +// lawsFile.setFileName(fileOriName+".pdf"); +// lawsFile.setFileSuffix("pdf"); +// countSuccess = sarLawsFileDao.insertSelective(lawsFile); +// } else if (SarTypeEnum.BUSINESS.getValue().equals(convertMq.getConvertType())) { +// SarBussStandFile lawsFile = new SarBussStandFile(); +// lawsFile.setId(UUID.randomUUID(20)); +// lawsFile.setStandId(convertMq.getLawsId()); +// lawsFile.setResId(convertMq.getResId()); +// lawsFile.setAttId(pdfId); +// lawsFile.setOriAttId(convertMq.getOriAttId()); +// lawsFile.setUseModule(UseModuleEnum.WEB_FILE.getValue()); +// lawsFile.setStandFileClassify(convertMq.getStandFileClassify()); +// lawsFile.setFileName(fileOriName+".pdf"); +// lawsFile.setFileSuffix("pdf"); +// lawsFile.setValidFlag(0); +// lawsFile.setCreationTime(new Date()); +// lawsFile.setModifyTime(new Date()); +// countSuccess = sarBussStandFileEODao.insertSelective(lawsFile); +// } +// else if (SarTypeEnum.RECORDS.getValue().equals(convertMq.getConvertType())) { +//// SarBussRecordsFileEO lawsFile = new SarBussRecordsFileEO(); +//// lawsFile.setId(UUID.randomUUID(20)); +//// lawsFile.setRecordsId(convertMq.getLawsId()); +//// lawsFile.setResId(convertMq.getResId()); +//// lawsFile.setAttId(pdfId); +//// lawsFile.setOriAttId(convertMq.getOriAttId()); +//// lawsFile.setUseModel(UseModuleEnum.WEB_FILE.getValue()); +//// lawsFile.setRecordsFileClassify(convertMq.getStandFileClassify()); +//// lawsFile.setFileName(fileOriName+".pdf"); +//// lawsFile.setFileSuffix("pdf"); +//// lawsFile.setValidFlag("0"); +//// lawsFile.setCreationTime(new Date()); +//// lawsFile.setModifyTime(new Date()); +//// countSuccess = sarBussRecordsFileEODao.insertSelective(lawsFile); +// }else { +//// SarFileSplitItemsFileEO lawsFile = new SarFileSplitItemsFileEO(); +//// lawsFile.setId(UUID.randomUUID(20)); +//// lawsFile.setStandId(convertMq.getLawsId()); +//// lawsFile.setResId(convertMq.getResId()); +//// lawsFile.setAttId(pdfId); +////// lawsFile.setOriAttId(convertMq.getOriAttId()); +//// lawsFile.setUseModel(UseModuleEnum.WEB_FILE.getValue()); +//// lawsFile.setValidFlag(0); +//// lawsFile.setCreationTime(new Date()); +//// lawsFile.setModifyTime(new Date()); +//// countSuccess = sarFileSplitItemsFileEODao.insertSelective(lawsFile); +// } +// return countSuccess; +// } +// +// /** +// * 文档转换逻辑 +// * @param attFileEO +// */ +// public void insertOrUpdateStandInfo(AttFileEO attFileEO){ +// +// } +// +// +//} diff --git a/adc-da-convert/src/main/java/com/adc/da/convert/otConvert/controller/OtConvertController.java b/adc-da-convert/src/main/java/com/adc/da/convert/otConvert/controller/OtConvertController.java index 054a1c48..1319afe8 100644 --- a/adc-da-convert/src/main/java/com/adc/da/convert/otConvert/controller/OtConvertController.java +++ b/adc-da-convert/src/main/java/com/adc/da/convert/otConvert/controller/OtConvertController.java @@ -1,18 +1,38 @@ package com.adc.da.convert.otConvert.controller; +import com.adc.da.att.controller.AttFileEOController; import com.adc.da.att.entity.AttFileEO; +import com.adc.da.att.service.IAttFileEOService; +import com.adc.da.att.vo.AttFileVo; +import com.adc.da.convert.common.AsposeOfficeConvertUtils; import com.adc.da.convert.mq.CreateConvertMQService; +import com.adc.da.convert.otConvert.service.IOtConvertService; import com.adc.da.util.http.ResponseMessage; import com.adc.da.util.http.Result; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.*; import com.adc.da.convert.otConvert.entity.OtConvert; import io.swagger.annotations.Api; -import org.springframework.web.bind.annotation.RestController; import com.adc.da.base.web.BaseController; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** *

@@ -24,12 +44,51 @@ import com.adc.da.base.web.BaseController; */ @RestController @Api(tags = "|OtConvert| 文档转换") -@RequestMapping("/OtConvert") +@RequestMapping("/${restPath}/OtConvert") public class OtConvertController extends BaseController { + private static final Logger logger = LoggerFactory.getLogger(OtConvertController.class); + + @Value("${file.path}") + private String filePath;//文件存储路径 + + @Value("${upload.file.white.lists}") + private String uploadFileWhiteLists; //上传文件白名单 + + @Autowired + private IOtConvertService iOtConvertService; + + @Autowired + private IAttFileEOService attFileEOService; + @Autowired private CreateConvertMQService createConvertMQService; + @ApiOperation(value = "|OtActConvertEO|根据文件ID获取流程转换文档") + @GetMapping(value = "/getConvertFileByAttId") + public ResponseMessage getConvertFileByAttId(String attId) throws Exception { + // 根据attId查到地址 + if(StringUtils.isNotBlank(attId)){ + QueryWrapper wrapper = new QueryWrapper(); + wrapper.eq("ACT_FILE_ID",attId); + List resultList = iOtConvertService.list(wrapper); + if(resultList!=null && !resultList.isEmpty()){ + OtConvert convertEO = resultList.get(0); + if(StringUtils.isNotBlank(convertEO.getConvertFileId())){ + AttFileEO attFileEO = attFileEOService.getFileInfo(convertEO.getConvertFileId()); + convertEO.setConvertFileInfo(attFileEO); + return Result.success(convertEO); + }else{ + return Result.success("-100","查询的转件文件未找到,请检查状态",convertEO); + } + }else{ + return Result.error("-1","查询的转换记录不存在",null); + } + }else{ + return Result.error("-1","查询的转换文档ID不存在",null); + } + } + /** * @Author super_liu * @Description 查询文件信息 diff --git a/adc-da-convert/src/main/java/com/adc/da/convert/otConvert/entity/OtActConvertEO.java b/adc-da-convert/src/main/java/com/adc/da/convert/otConvert/entity/OtActConvertEO.java new file mode 100644 index 00000000..a6d00c6d --- /dev/null +++ b/adc-da-convert/src/main/java/com/adc/da/convert/otConvert/entity/OtActConvertEO.java @@ -0,0 +1,144 @@ +package com.adc.da.convert.otConvert.entity; + +import com.adc.da.att.entity.AttFileEO; +import com.adc.da.base.entity.BaseEntity; + +import java.util.Date; + +/** + * 功能:OT_ACT_CONVERT OtActConvertEOEntity
+ * 作者:code generator
+ * 日期: 2021-03-19
+ * 版权所有:版权归北京卡达克数据技术中心所有。
+ */ +public class OtActConvertEO extends BaseEntity { + + private String id; + private String actFileId; + private String convertState; + private String convertFileId; + @org.springframework.format.annotation.DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") + private Date createTime; + @org.springframework.format.annotation.DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") + private Date modifyTime; + + // 转换后文件信息 + private AttFileEO ConvertFileInfo; + + + + /** + * java字段名转换为原始数据库列名。如果不存在则返回null
+ *

字段列表:

+ *
  • id -> id
  • + *
  • actFileId -> act_file_id
  • + *
  • convertState -> convert_state
  • + *
  • convertFileId -> convert_file_id
  • + *
  • createTime -> create_time
  • + *
  • modifyTime -> modify_time
  • + */ + public static String fieldToColumn(String fieldName) { + if (fieldName == null) { return null; }; + switch (fieldName) { + case "id": return "id"; + case "actFileId": return "act_file_id"; + case "convertState": return "convert_state"; + case "convertFileId": return "convert_file_id"; + case "createTime": return "create_time"; + case "modifyTime": return "modify_time"; + default: return null; + } + } + + /** + * 原始数据库列名转换为java字段名。如果不存在则返回null
    + *

    字段列表:

    + *
  • id -> id
  • + *
  • act_file_id -> actFileId
  • + *
  • convert_state -> convertState
  • + *
  • convert_file_id -> convertFileId
  • + *
  • create_time -> createTime
  • + *
  • modify_time -> modifyTime
  • + */ + public static String columnToField(String columnName) { + if (columnName == null) { return null; }; + switch (columnName) { + case "id": return "id"; + case "act_file_id": return "actFileId"; + case "convert_state": return "convertState"; + case "convert_file_id": return "convertFileId"; + case "create_time": return "createTime"; + case "modify_time": return "modifyTime"; + default: return null; + } + } + + /** 主键 **/ + public String getId() { + return this.id; + } + + /** 主键 **/ + public void setId(String id) { + this.id = id; + } + + /** 流程中待转换文件ID **/ + public String getActFileId() { + return this.actFileId; + } + + /** 流程中待转换文件ID **/ + public void setActFileId(String actFileId) { + this.actFileId = actFileId; + } + + /** 转换状态:LODING:待转换 SUCCESS:成功 ERROR:错误 **/ + public String getConvertState() { + return this.convertState; + } + + /** 转换状态:LODING:待转换 SUCCESS:成功 ERROR:错误 **/ + public void setConvertState(String convertState) { + this.convertState = convertState; + } + + /** 转换后文件ID **/ + public String getConvertFileId() { + return this.convertFileId; + } + + /** 转换后文件ID **/ + public void setConvertFileId(String convertFileId) { + this.convertFileId = convertFileId; + } + + /** 数据创建时间 **/ + public Date getCreateTime() { + return this.createTime; + } + + /** 数据创建时间 **/ + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + /** 数据修改时间 **/ + public Date getModifyTime() { + return this.modifyTime; + } + + /** 数据修改时间 **/ + public void setModifyTime(Date modifyTime) { + this.modifyTime = modifyTime; + } + + + public AttFileEO getConvertFileInfo() { + return ConvertFileInfo; + } + + public void setConvertFileInfo(AttFileEO convertFileInfo) { + ConvertFileInfo = convertFileInfo; + } +} diff --git a/adc-da-convert/src/main/java/com/adc/da/convert/otConvert/entity/OtConvert.java b/adc-da-convert/src/main/java/com/adc/da/convert/otConvert/entity/OtConvert.java index 2d4e6567..317086c6 100644 --- a/adc-da-convert/src/main/java/com/adc/da/convert/otConvert/entity/OtConvert.java +++ b/adc-da-convert/src/main/java/com/adc/da/convert/otConvert/entity/OtConvert.java @@ -1,5 +1,6 @@ package com.adc.da.convert.otConvert.entity; +import com.adc.da.att.entity.AttFileEO; import com.adc.da.base.entity.BaseEntity; import com.baomidou.mybatisplus.annotation.TableId; @@ -62,5 +63,7 @@ public class OtConvert extends BaseEntity { @TableField("VALID_FLAG") private Integer validFlag; - + // 转换后文件信息 + @TableField(exist = false) + private AttFileEO ConvertFileInfo; } diff --git a/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/WebMvcConfig.java b/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/WebMvcConfig.java index 85625c89..3bbea18e 100644 --- a/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/WebMvcConfig.java +++ b/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/WebMvcConfig.java @@ -63,6 +63,10 @@ public class WebMvcConfig implements WebMvcConfigurer { addInterceptor.excludePathPatterns("/api/sarStandUnqualified/sar-stand-unqualified/exportStandUnqulifiedExcel"); //文件预览 addInterceptor.excludePathPatterns("/api/att/attFile/getFileInfo"); + // onlyOffice 回调 + addInterceptor.excludePathPatterns("/api/att/attFile/recieveFile"); + + addInterceptor.excludePathPatterns("/api/att/attFile/getSyncPdfFileInfo"); //附件下载 addInterceptor.excludePathPatterns("/api/att/attFile/downloadFileForSar"); //水印下载 diff --git a/adc-da-main/src/main/resources/application.properties b/adc-da-main/src/main/resources/application.properties index 75fa37d5..605d2d3d 100644 --- a/adc-da-main/src/main/resources/application.properties +++ b/adc-da-main/src/main/resources/application.properties @@ -132,8 +132,11 @@ verifyCodeMode=1 # ============================================================================= # file模块上传文件的服务器地址 file.path=/data/slrs/file -# 文件下载地址参数(弃用) -file.downloadUrl= + +stand.edit.file.path = /usr/laws/file/ +# onlyoffice 预览地址 +file.downloadUrl=http://10.100.5.116:1080/file/ + #上传文件白名单-以,分隔 upload.file.white.lists = doc,docx,xls,xlsx,pdf,PDF,png,jpg,pptx,ppt diff --git a/adc-da-slrs/src/main/java/com/adc/da/scheduled/entity/WarningEO.java b/adc-da-slrs/src/main/java/com/adc/da/scheduled/entity/WarningEO.java index 20868a38..4dddeadc 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/scheduled/entity/WarningEO.java +++ b/adc-da-slrs/src/main/java/com/adc/da/scheduled/entity/WarningEO.java @@ -31,5 +31,6 @@ public class WarningEO extends EarlyWarningEO { private String standYear; + private String issueTime; } diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/controller/SarModelTreeController.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/controller/SarModelTreeController.java index f5fc6db7..aaf58537 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/controller/SarModelTreeController.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/controller/SarModelTreeController.java @@ -3,6 +3,7 @@ package com.adc.da.slrs.sarModelTree.controller; import com.adc.da.http.ResponseMessage; import com.adc.da.http.Result; +import com.adc.da.slrs.sarModelTree.entity.SarModuleTree; import com.adc.da.slrs.sarModelTree.service.ISarModelTreeService; import com.adc.da.slrs.sarModelTree.service.ISarModuleTreeService; import com.adc.da.slrs.sarStandProjectLibrary.entity.myResponse.Head; @@ -38,17 +39,18 @@ public class SarModelTreeController extends BaseController { @ApiOperation("查询父所有资源") @GetMapping("/list") public ResponseMessage> getAll(){ - List tsResources = iSarModelTreeService.getAll(null); -// TODO List tsResources = iSarModuleTreeService.getAll(null); +// List tsResources = iSarModuleTreeService.getAll(null); + List tsResources = iSarModelTreeService.getAll(null); return Result.success(tsResources); } @ApiOperation("根据父ID查询子所有资源") @GetMapping("/childByList") - public ResponseMessage> childByList(String ids){ - SarModelTree tree = new SarModelTree(); - tree.setId(ids); - List tsResources = iSarModelTreeService.recursionGetChildren(tree); + public ResponseMessage> childByList(SarModelTree parentTree){ +// List tsResources = iSarModuleTreeService.recursionGetChildren(parentTree); + + List tsResources = iSarModelTreeService.recursionGetChildren(parentTree); + return Result.success(tsResources); } diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/entity/SarModelTree.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/entity/SarModelTree.java index cbdd10d2..0b68d34a 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/entity/SarModelTree.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/entity/SarModelTree.java @@ -13,7 +13,7 @@ import java.util.List; /** *

    - * + * *

    * * @author super_liu diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/entity/SarModuleTree.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/entity/SarModuleTree.java index 95dcdca1..227dc6d1 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/entity/SarModuleTree.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/entity/SarModuleTree.java @@ -70,7 +70,13 @@ public class SarModuleTree { @TableField("CREATIONDATE") private String creationdate; + @TableField(exist = false) + private Integer level; + @TableField(exist = false) + private String model; + @TableField(exist = false) + private String nextCondition; } diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/service/ISarModuleTreeService.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/service/ISarModuleTreeService.java index f84026c1..44254478 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/service/ISarModuleTreeService.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/service/ISarModuleTreeService.java @@ -1,15 +1,16 @@ package com.adc.da.slrs.sarModelTree.service; import com.adc.da.slrs.sarModelTree.entity.SarModelTree; +import com.adc.da.slrs.sarModelTree.entity.SarModuleTree; import com.adc.da.slrs.sarStandProjectLibrary.entity.myResponse.Head; import java.util.List; public interface ISarModuleTreeService { - List getAll(SarModelTree sarModelTree); + List getAll(SarModuleTree root); - List recursionGetChildren(SarModelTree parent); + List recursionGetChildren(SarModuleTree parent); public Head analysisJsonAndStorage(String json); diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/service/impl/SarModelTreeServiceImpl.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/service/impl/SarModelTreeServiceImpl.java index a9703566..0635dd2d 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/service/impl/SarModelTreeServiceImpl.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/service/impl/SarModelTreeServiceImpl.java @@ -32,6 +32,9 @@ public class SarModelTreeServiceImpl extends ServiceImpl{ + item.setId(item.getName()); + }); return list; } @@ -44,11 +47,16 @@ public class SarModelTreeServiceImpl extends ServiceImpl recursionGetChildren(SarModelTree parent){ QueryWrapper sarMenuQueryWrapper=new QueryWrapper<>(); sarMenuQueryWrapper.orderByAsc("SORT"); - sarMenuQueryWrapper.in("PID",parent.getId()); +// sarMenuQueryWrapper.in("PID",parent.getId()); + sarMenuQueryWrapper.eq("PID",parent.getId()); List children=this.baseMapper.selectList(sarMenuQueryWrapper); - for(SarModelTree sarMenu:children){ - sarMenu.setChildren(recursionGetChildren((sarMenu))); - } +// for(SarModelTree sarMenu:children){ +// sarMenu.setChildren(recursionGetChildren((sarMenu))); +// } + + children.forEach(item->{ + item.setId(item.getName()); + }); return children; } } diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/service/impl/SarModuleTreeServiceImpl.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/service/impl/SarModuleTreeServiceImpl.java index 553be0fb..e5119153 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/service/impl/SarModuleTreeServiceImpl.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarModelTree/service/impl/SarModuleTreeServiceImpl.java @@ -15,9 +15,11 @@ import com.google.gson.JsonParser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.awt.event.MouseAdapter; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.logging.Level; import java.util.stream.Collectors; @Service @@ -27,16 +29,27 @@ public class SarModuleTreeServiceImpl extends ServiceImpl getAll(SarModelTree sarModelTree) { + public List getAll(SarModuleTree root) { QueryWrapper treeQueryWrapper = new QueryWrapper<>(); - treeQueryWrapper.groupBy("FTVSTYPE1"); - List moduleTreeList = this.baseMapper.selectList(treeQueryWrapper); + treeQueryWrapper.select("FTVSTYPE1") + .groupBy("FTVSTYPE1"); + + List> moduleTreeList = this.baseMapper.selectMaps(treeQueryWrapper); + + List collect = moduleTreeList.stream() + .map(item -> { + SarModuleTree sarModuleTree = new SarModuleTree(); + sarModuleTree.setNextCondition(item.get("FTVSTYPE1").toString()); + sarModuleTree.setLevel(1); + sarModuleTree.setModel(item.get("FTVSTYPE1").toString()); + return sarModuleTree; + }).collect(Collectors.toList()); + //返回转换元素后的数组 - return listTransform(moduleTreeList); + return collect; } /** @@ -45,20 +58,47 @@ public class SarModuleTreeServiceImpl extends ServiceImpl recursionGetChildren(SarModelTree parent) { + public List recursionGetChildren(SarModuleTree parent) { QueryWrapper treeQueryWrapper = new QueryWrapper<>(); - treeQueryWrapper.eq("GUID",parent.getId()); - List moduleTreeList = this.baseMapper.selectList(treeQueryWrapper); + Integer level =parent.getLevel(); + + switch (parent.getLevel()){ + case 1: + level=2; + break; + case 6: + return null; + } + + String column="FTVSTYPE"+(level+1); + + treeQueryWrapper.select(column) + .eq("FTVSTYPE"+parent.getLevel(),parent.getNextCondition()) + .groupBy(column); + + List> moduleTreeList = this.baseMapper.selectMaps(treeQueryWrapper); + + Integer finalLevel = level; + List collect = moduleTreeList.stream() + .map(item -> { + SarModuleTree sarModuleTree = new SarModuleTree(); + sarModuleTree.setNextCondition(item.get(column).toString()); //查询子节点条件 + sarModuleTree.setLevel(finalLevel + 1); + //拼接前端显示名称 +// switch (finalLevel){ +// case 3: +// sarModuleTree.setModel(item.get(column).toString());//前端显示名称 +// break; +// case +// } - Map> collect = moduleTreeList.stream().collect(Collectors.groupingBy(SarModuleTree::getFtvstype1)); - collect.forEach((k, v)->{ - SarModelTree modelTree = new SarModelTree(); - //TODO 生成树型结构 -// modelTree - }); - return null; + return sarModuleTree; + }).collect(Collectors.toList()); + + + return collect; } @Override diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandItems/service/impl/SarStandItemsServiceImpl.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandItems/service/impl/SarStandItemsServiceImpl.java index 1d823c88..e71dcf59 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandItems/service/impl/SarStandItemsServiceImpl.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandItems/service/impl/SarStandItemsServiceImpl.java @@ -155,24 +155,24 @@ public class SarStandItemsServiceImpl extends ServiceImpl pageInfo = null; - try { - pageInfo = sarStandardsInfoService.getSarStandardsInfoPageBak(page); - } catch (Exception e) { - e.printStackTrace(); - } +// try { +// pageInfo = sarStandardsInfoService.getSarStandardsInfoPageBak(page); +// } catch (Exception e) { +// e.printStackTrace(); +// } List standId = new ArrayList<>(); - for (SarStandardsInfo standardsInfo : pageInfo){ - if (standardsInfo.getAttrInfoCaseMap().get("FBGBJBD")!=null || standardsInfo.getAttrInfoCaseMap().get("fbgbjbd")!=null){ - standId.add(standardsInfo.getId()); - } - } +// for (SarStandardsInfo standardsInfo : pageInfo){ +//// if (standardsInfo.getAttrInfoCaseMap().get("FBGBJBD")!=null || standardsInfo.getAttrInfoCaseMap().get("fbgbjbd")!=null){ +// standId.add(standardsInfo.getId()); +//// } +// } List list=new ArrayList<>(); - if (standId==null || standId.size()==0){ - list = null; - }else { +// if (standId==null || standId.size()==0){ +// list = null; +// }else { list = sarLawsAttrDetailedListDao.selectLawsByIdC((findStandDto.getPage()-1)*findStandDto.getSize(),findStandDto.getPage()*findStandDto.getSize(),standId,findStandDto.getStandName(), findStandDto.getStandType(),findStandDto.getFileType()); - } +// } IPage page1=new Page<>(); page1.setRecords(list); page1.setTotal(sarLawsAttrDetailedListDao.selectLawsByIdCount(standId,findStandDto.getStandName(),findStandDto.getStandType(),findStandDto.getFileType()).size()); @@ -195,6 +195,7 @@ public class SarStandItemsServiceImpl extends ServiceImpl findAllItems(String type,String[] ids){ List list=dao.selectAllItemsByIds(type,ids); List res=new ArrayList<>(); + List chinese=new ArrayList<>(); if (null == list || list.isEmpty()){ return list; }else { @@ -206,20 +207,24 @@ public class SarStandItemsServiceImpl extends ServiceImpl0){ mark=mark.substring(0,a); } - if (null != map.get(Integer.valueOf(mark))){ - map.get(Integer.valueOf(mark)).add(sarStandItemsDto); - }else { - integerList.add(Integer.valueOf(mark)); - List middle=new ArrayList<>(); - middle.add(sarStandItemsDto); - map.put(Integer.valueOf(mark),middle); - } + try { + if (null != map.get(Integer.valueOf(mark))) { + map.get(Integer.valueOf(mark)).add(sarStandItemsDto); + } else { + integerList.add(Integer.valueOf(mark)); + List middle = new ArrayList<>(); + middle.add(sarStandItemsDto); + map.put(Integer.valueOf(mark), middle); + } + }catch (Exception e){ + chinese.add(sarStandItemsDto); + } }); Collections.sort(integerList); integerList.forEach(integer -> { res.addAll(map.get(integer)); }); - + res.addAll(chinese); return res; } } diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandUnqualified/controller/SarStandUnqualifiedController.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandUnqualified/controller/SarStandUnqualifiedController.java index a0994984..c63c1e8d 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandUnqualified/controller/SarStandUnqualifiedController.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandUnqualified/controller/SarStandUnqualifiedController.java @@ -56,6 +56,29 @@ public class SarStandUnqualifiedController extends BaseController add(@RequestBody SarStandUnqualified sarStandUnqualified){ + sarStandUnqualified.setCreateTime(new Date()); + if (sarStandUnqualifiedService.save(sarStandUnqualified)) { + return Result.success("新增成功"); + } + else{ + return Result.error("新增失败"); + } + } + + @ApiOperation("未符合项整改新增") + @PostMapping("/updateOne") + public ResponseMessage update(@RequestBody SarStandUnqualified sarStandUnqualified){ + if (sarStandUnqualifiedService.updateById(sarStandUnqualified)) { + return Result.success("新增成功"); + } + else{ + return Result.error("新增失败"); + } + } + /** * 分页查询未符合项 * @param sarStandUnqualifiedPage:筛选、分页信息 diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/controller/EarlyWarningEOController.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/controller/EarlyWarningEOController.java index c364e76e..3b034a1f 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/controller/EarlyWarningEOController.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/controller/EarlyWarningEOController.java @@ -5,6 +5,7 @@ import com.adc.da.base.web.BaseController; import com.adc.da.http.ResponseMessage; import com.adc.da.http.Result; import com.adc.da.slrs.sarStandWarning.entity.EarlyWarningEO; +import com.adc.da.slrs.sarStandWarning.entity.StandWarningEO; import com.adc.da.slrs.sarStandWarning.service.Impl.EarlyWarningEOServiceImpl; import com.baomidou.mybatisplus.core.metadata.IPage; @@ -41,7 +42,7 @@ public class EarlyWarningEOController extends BaseController { * @author zj * date 2021-06-15 **/ - @GetMapping("/StandWarning") + @GetMapping("/${restPath}/StandWarning") @ApiOperation("标准预警查询") public ResponseMessage newPageInfo(@RequestParam(defaultValue = "1", value = "newStandPage")int newStandPage, @RequestParam(defaultValue = "10", value = "newStandPageSize") int newStandPageSize, @RequestParam(defaultValue = "1", value = "oldStandPage")int oldStandPage, @RequestParam(defaultValue = "10", value = "oldStandPageSize") int oldStandPageSize, @@ -53,6 +54,16 @@ public class EarlyWarningEOController extends BaseController { IPage list4 = earlyWarningEOService.oldItemsQuery(oldItemsPage,oldItemsPageSize,earlyWarningEO);//在产车条款预警 return getResponseMessage(list1, list2, list3, list4); } + + @GetMapping("/getStandWarning") + @ApiOperation("标准预警查询") + public ResponseMessage> getStandWaring(StandWarningEO queryPageEO){ + IPage standWarning = earlyWarningEOService.getStandWarning(queryPageEO); + return Result.success(standWarning); + } + + + private ResponseMessage getResponseMessage(IPage list1, IPage list2, IPage list3, IPage list4) { List> listMap = new ArrayList>(); Map map = new HashMap(); @@ -71,7 +82,7 @@ public class EarlyWarningEOController extends BaseController { * date 2021-06-15 **/ @GetMapping("/ChangePermissions") - @ApiOperation("更改权限") + @ApiOperation("取消预警") public ResponseMessage ChangePermissions(String id) { String power = earlyWarningEOService.ChangePermissions(id); return Result.success("200",power); diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/dao/EarlyWarningEODao.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/dao/EarlyWarningEODao.java index ff0617e0..853cf4d4 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/dao/EarlyWarningEODao.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/dao/EarlyWarningEODao.java @@ -2,14 +2,13 @@ package com.adc.da.slrs.sarStandWarning.dao; import com.adc.da.slrs.sarStandWarning.entity.EarlyWarningEO; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.adc.da.slrs.sarStandWarning.entity.StandWarningEO; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.core.toolkit.Constants; import org.apache.ibatis.annotations.Param; public interface EarlyWarningEODao extends BaseMapper { - IPage selectWarningPage(IPage page, @Param(Constants.WRAPPER) QueryWrapper queryWrapper); + IPage selectWarningPage(IPage page, @Param("waringEO") StandWarningEO warningEO); } diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/entity/EarlyWarningEO.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/entity/EarlyWarningEO.java index 4da5206d..d8e1839b 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/entity/EarlyWarningEO.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/entity/EarlyWarningEO.java @@ -5,6 +5,8 @@ import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.annotations.Tag; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; @@ -23,21 +25,27 @@ public class EarlyWarningEO extends BaseEntity { private static final long serialVersionUID = 1L; + @ApiModelProperty("id") @TableId("ID") private String id; + @ApiModelProperty("标准id") @TableField("STAND_ID") private String standId; + @ApiModelProperty("标准类别") @TableField("STAND_TYPE") private String standType; + @ApiModelProperty("标准号") @TableField("STAND_CODE") private String standCode; + @ApiModelProperty("标准名称") @TableField("STAND_NAME") private String standName; + @ApiModelProperty("发布日期") @TableField("PUT_TIME") @DateTimeFormat(pattern="yyyy-MM-dd") private Date putTime; @@ -45,18 +53,23 @@ public class EarlyWarningEO extends BaseEntity { @TableField(exist = false) private Date lastTime; + @ApiModelProperty("适用车型") @TableField("APPLY_TYPE") private String applyType; + @ApiModelProperty("责任工程师") @TableField("DUTY_ENGINEER") private String dutyEngineer; + @ApiModelProperty("条款(分解单)id") @TableField("ITEMS_ID") private String itemsId; + @ApiModelProperty("条款(分解单)编号") @TableField("ITEMS_NUM") private String itemsNum; + @ApiModelProperty("条款(分解单)名称") @TableField("ITEMS_NAME") private String itemsName; @@ -72,7 +85,6 @@ public class EarlyWarningEO extends BaseEntity { @TableField("POWER") private String power; - @TableField(exist = false) - private String issueTime; + } diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/entity/StandWarningEO.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/entity/StandWarningEO.java new file mode 100644 index 00000000..b4c77336 --- /dev/null +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/entity/StandWarningEO.java @@ -0,0 +1,73 @@ +package com.adc.da.slrs.sarStandWarning.entity; + +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.experimental.Accessors; +import org.springframework.format.annotation.DateTimeFormat; + +import java.util.Date; + +@Data +@Accessors(chain = true) +public class StandWarningEO extends EarlyWarningEO { + private static final long serialVersionUID = 1L; + @ApiModelProperty("新车型实施日期") + @DateTimeFormat(pattern = "YYYY-MM-dd") + private String XCXSSRQ; + + @ApiModelProperty("在产车实施日期") + @DateTimeFormat(pattern = "YYYY-MM-dd") + private String ZCCSSRQ; + + @ApiModelProperty("实施日期") + @DateTimeFormat(pattern = "YYYY-MM-dd") + private String SSRQ; + + + private String standNum; + + private String standSort; + + private String standYear; + + private String issueTime; + + private Integer page; + + private Integer pageSize; + + @ApiModelProperty("范围查询新车型实施日期开始") + @DateTimeFormat(pattern = "YYYY-MM-dd") + private String startXCXSSRQ; + + @ApiModelProperty("范围查询新车型实施日期结束") + @DateTimeFormat(pattern = "YYYY-MM-dd") + private String endXCXSSRQ; + + @ApiModelProperty("范围查询在产车实施日期开始") + @DateTimeFormat(pattern = "YYYY-MM-dd") + private String startZCCSSRQ; + + @ApiModelProperty("范围查询在产车实施日期结束") + @DateTimeFormat(pattern = "YYYY-MM-dd") + private String endZCCSSRQ; + + @ApiModelProperty("范围查询实施日期开始") + @DateTimeFormat(pattern = "YYYY-MM-dd") + private String startSSRQ; + + + @ApiModelProperty("范围查询实施日期结束") + @DateTimeFormat(pattern = "YYYY-MM-dd") + private String endSSRQ; + + + @ApiModelProperty("范围查询发布日期开始") + @DateTimeFormat(pattern = "YYYY-MM-dd") + private String startPutTime; + + + @ApiModelProperty("范围查询发布日期结束") + @DateTimeFormat(pattern = "YYYY-MM-dd") + private String endPutTime; +} diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/service/EarlyWarningEOService.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/service/EarlyWarningEOService.java index c037a64c..89ce035e 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/service/EarlyWarningEOService.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/service/EarlyWarningEOService.java @@ -2,6 +2,7 @@ package com.adc.da.slrs.sarStandWarning.service; import com.adc.da.slrs.sarStandWarning.entity.EarlyWarningEO; +import com.adc.da.slrs.sarStandWarning.entity.StandWarningEO; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; @@ -16,4 +17,7 @@ public interface EarlyWarningEOService extends IService { IPage oldPolicyQuery(int current,int pageSize); String batchSave(List earlyWarningEOS); String ChangePermissions(String id); + + + IPage getStandWarning(StandWarningEO queryPage); } diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/service/Impl/EarlyWarningEOServiceImpl.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/service/Impl/EarlyWarningEOServiceImpl.java index e241936c..7ddabbbc 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/service/Impl/EarlyWarningEOServiceImpl.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarStandWarning/service/Impl/EarlyWarningEOServiceImpl.java @@ -4,6 +4,7 @@ package com.adc.da.slrs.sarStandWarning.service.Impl; import com.adc.da.scheduled.entity.DataDTO; import com.adc.da.slrs.sarStandWarning.dao.EarlyWarningEODao; import com.adc.da.slrs.sarStandWarning.entity.EarlyWarningEO; +import com.adc.da.slrs.sarStandWarning.entity.StandWarningEO; import com.adc.da.slrs.sarStandWarning.service.EarlyWarningEOService; import com.adc.da.sys.util.DateUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; @@ -106,6 +107,17 @@ public class EarlyWarningEOServiceImpl extends ServiceImpl getStandWarning(StandWarningEO queryPage) { + IPage iPage = new Page<>(queryPage.getPage(),queryPage.getPageSize()); + return earlyWarningEODao.selectWarningPage(iPage,queryPage); + } + private IPage getEarlyWarningEOIPage(int current,int pageSize, QueryWrapper wrapper) { wrapper.eq("power",1); Page page = new Page<>(current, pageSize); @@ -144,4 +156,8 @@ public class EarlyWarningEOServiceImpl extends ServiceImpl { @ApiOperation("根据父ID查询子所有资源") @GetMapping("/childByList") - public ResponseMessage> childByList(String ids){ - SarVppsTree tree = new SarVppsTree(); - tree.setId(ids); - List tsResources = iSarVppsTreeService.recursionGetChildren(tree); + public ResponseMessage> childByList(SarVppsTree parent){ +// SarVppsTree tree = new SarVppsTree(); +// tree.setId(ids); + List tsResources = iSarVppsTreeService.recursionGetChildren(parent); return Result.success(tsResources); } diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarVppsTree/entity/SarVppsTree.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarVppsTree/entity/SarVppsTree.java index e9fb22cf..8e31ac90 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarVppsTree/entity/SarVppsTree.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarVppsTree/entity/SarVppsTree.java @@ -13,7 +13,7 @@ import java.util.List; /** *

    - * + * *

    * * @author super_liu @@ -66,6 +66,18 @@ public class SarVppsTree extends BaseEntity { @TableField(exist = false) private String parentIdsName; + @ApiModelProperty("层级") + @TableField("LEVEL") + private Integer level; + + @ApiModelProperty("类型") + @TableField("TYPE") + private String type; + + @ApiModelProperty("查询子节点条件") + @TableField(exist = false) + private String nextCondition; + @TableField(exist=false) private List roleIds; @@ -73,4 +85,6 @@ public class SarVppsTree extends BaseEntity { private List childMenuIds; + + } diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarVppsTree/service/impl/SarVppsTreeServiceImpl.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarVppsTree/service/impl/SarVppsTreeServiceImpl.java index 32c8c76d..f5986c6d 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/sarVppsTree/service/impl/SarVppsTreeServiceImpl.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/sarVppsTree/service/impl/SarVppsTreeServiceImpl.java @@ -27,8 +27,14 @@ public class SarVppsTreeServiceImpl extends ServiceImpl getAll(SarVppsTree sarVppsTree) { QueryWrapper tsResourceQueryWrapper=new QueryWrapper<>(); - tsResourceQueryWrapper.isNull("PID"); + tsResourceQueryWrapper.eq("TYPE",sarVppsTree.getType()) + .eq("LEVEL",0); List list = this.baseMapper.selectList(tsResourceQueryWrapper); + + list.forEach(item->{ + item.setCode(item.getVppsCode()+item.getChineseName()); + item.setId("10"); + }); // for(SarVppsTree tree:list){ // tree.setChildren(recursionGetChildren((tree))); // } @@ -44,11 +50,16 @@ public class SarVppsTreeServiceImpl extends ServiceImpl recursionGetChildren(SarVppsTree parent){ QueryWrapper sarMenuQueryWrapper=new QueryWrapper<>(); sarMenuQueryWrapper.orderByAsc("SORT"); - sarMenuQueryWrapper.in("PID",parent.getId()); + + sarMenuQueryWrapper.eq("LEVEL", parent.getLevel()+1) + .eq("TYPE",parent.getType()) + .like("VPPS_CODE",parent.getId()); List children=this.baseMapper.selectList(sarMenuQueryWrapper); - for(SarVppsTree sarMenu:children){ - sarMenu.setChildren(recursionGetChildren((sarMenu))); - } + + children.forEach(item->{ + item.setId(item.getVppsCode()); + item.setCode(item.getVppsCode()+item.getChineseName()); + }); return children; } } diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/EventUtils/DiffMatchPatch.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/EventUtils/DiffMatchPatch.java new file mode 100644 index 00000000..0ab2356d --- /dev/null +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/EventUtils/DiffMatchPatch.java @@ -0,0 +1,2276 @@ +package com.adc.da.slrs.standardSplit.EventUtils; + +/** + * @Description: TODO + * @author: super_liu + * @date: 2021年11月28日 12:30 + */ +/* + * Diff Match and Patch + * + * Copyright 2006 Google Inc. + * http://code.google.com/p/google-diff-match-patch/ + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +/* + * Functions for diff, match and patch. + * Computes the difference between two texts to create a patch. + * Applies the patch onto another text, allowing for errors. + * + * @author fraser@google.com (Neil Fraser) + */ + +/** + * Class containing the diff, match and patch methods. + * Also contains the behaviour settings. + */ +@SuppressWarnings("all") +public class DiffMatchPatch { + + // Defaults. + // Set these on your diff_match_patch instance to override the defaults. + + /** + * Number of seconds to map a diff before giving up (0 for infinity). + */ + public float Diff_Timeout = 1.0f; + /** + * Cost of an empty edit operation in terms of edit characters. + */ + public short Diff_EditCost = 4; + /** + * The size beyond which the double-ended diff activates. + * Double-ending is twice as fast, but less accurate. + */ + public short Diff_DualThreshold = 32; + /** + * At what point is no match declared (0.0 = perfection, 1.0 = very loose). + */ + public float Match_Threshold = 0.5f; + /** + * How far to search for a match (0 = exact location, 1000+ = broad match). + * A match this many characters away from the expected location will add + * 1.0 to the score (0.0 is a perfect match). + */ + public int Match_Distance = 1000; + /** + * When deleting a large block of text (over ~64 characters), how close does + * the contents have to match the expected contents. (0.0 = perfection, + * 1.0 = very loose). Note that Match_Threshold controls how closely the + * end points of a delete need to match. + */ + public float Patch_DeleteThreshold = 0.5f; + /** + * Chunk size for context length. + */ + public short Patch_Margin = 4; + /** + * The number of bits in an int. + */ + private int Match_MaxBits = 32; + + /** + * Internal class for returning results from diff_linesToChars(). + * Other less paranoid languages just use a three-element array. + */ + protected static class LinesToCharsResult { + protected String chars1; + protected String chars2; + protected List lineArray; + + protected LinesToCharsResult(String chars1, String chars2, + List lineArray) { + this.chars1 = chars1; + this.chars2 = chars2; + this.lineArray = lineArray; + } + } + // DIFF FUNCTIONS + /** + * The data structure representing a diff is a Linked list of Diff objects: + * {Diff(Operation.DELETE, "Hello"), Diff(Operation.INSERT, "Goodbye"), + * Diff(Operation.EQUAL, " world.")} + * which means: delete "Hello", add "Goodbye" and keep " world." + */ + public enum Operation { + DELETE, INSERT, EQUAL + } + /** + * Find the differences between two texts. + * Run a faster slightly less optimal diff + * This method allows the 'checklines' of diff_main() to be optional. + * Most of the time checklines is wanted, so default to true. + * @param text1 Old string to be diffed. + * @param text2 New string to be diffed. + * @return Linked List of Diff objects. + */ + public LinkedList diff_main(String text1, String text2) { + return diff_main(text1, text2, true); + } + /** + * Find the differences between two texts. Simplifies the problem by + * stripping any common prefix or suffix off the texts before diffing. + * @param text1 Old string to be diffed. + * @param text2 New string to be diffed. + * @param checklines Speedup flag. If false, then don't run a + * line-level diff first to identify the changed areas. + * If true, then run a faster slightly less optimal diff + * @return Linked List of Diff objects. + */ + public LinkedList diff_main(String text1, String text2, boolean checklines) { + // Check for equality (speedup) + LinkedList diffs; + if (text1.equals(text2)) { + diffs = new LinkedList(); + diffs.add(new Diff(Operation.EQUAL, text1)); + return diffs; + } + // Trim off common prefix (speedup) + int commonlength = diff_commonPrefix(text1, text2); + String commonprefix = text1.substring(0, commonlength); + text1 = text1.substring(commonlength); + text2 = text2.substring(commonlength); + // Trim off common suffix (speedup) + commonlength = diff_commonSuffix(text1, text2); + String commonsuffix = text1.substring(text1.length() - commonlength); + text1 = text1.substring(0, text1.length() - commonlength); + text2 = text2.substring(0, text2.length() - commonlength); + // Compute the diff on the middle block + diffs = diff_compute(text1, text2, checklines); + + // Restore the prefix and suffix + if (commonprefix.length() != 0) { + diffs.addFirst(new Diff(Operation.EQUAL, commonprefix)); + } + if (commonsuffix.length() != 0) { + diffs.addLast(new Diff(Operation.EQUAL, commonsuffix)); + } + diff_cleanupMerge(diffs); + return diffs; + } + /** + * Find the differences between two texts. Assumes that the texts do not + * have any common prefix or suffix. + * @param text1 Old string to be diffed. + * @param text2 New string to be diffed. + * @param checklines Speedup flag. If false, then don't run a + * line-level diff first to identify the changed areas. + * If true, then run a faster slightly less optimal diff + * @return Linked List of Diff objects. + */ + protected LinkedList diff_compute(String text1, String text2,boolean checklines) { + LinkedList diffs = new LinkedList(); + if (text1.length() == 0) { + // Just add some text (speedup) + diffs.add(new Diff(Operation.INSERT, text2)); + return diffs; + } + if (text2.length() == 0) { + // Just delete some text (speedup) + diffs.add(new Diff(Operation.DELETE, text1)); + return diffs; + } + String longtext = text1.length() > text2.length() ? text1 : text2; + String shorttext = text1.length() > text2.length() ? text2 : text1; + int i = longtext.indexOf(shorttext); + if (i != -1) { + // Shorter text is inside the longer text (speedup) + Operation op = (text1.length() > text2.length()) ? + Operation.DELETE : Operation.INSERT; + diffs.add(new Diff(op, longtext.substring(0, i))); + diffs.add(new Diff(Operation.EQUAL, shorttext)); + diffs.add(new Diff(op, longtext.substring(i + shorttext.length()))); + return diffs; + } + longtext = shorttext = null; // Garbage collect. + // Check to see if the problem can be split in two. + String[] hm = diff_halfMatch(text1, text2); + if (hm != null) { + // A half-match was found, sort out the return data. + String text1_a = hm[0]; + String text1_b = hm[1]; + String text2_a = hm[2]; + String text2_b = hm[3]; + String mid_common = hm[4]; + // Send both pairs off for separate processing. + LinkedList diffs_a = diff_main(text1_a, text2_a, checklines); + LinkedList diffs_b = diff_main(text1_b, text2_b, checklines); + // Merge the results. + diffs = diffs_a; + diffs.add(new Diff(Operation.EQUAL, mid_common)); + diffs.addAll(diffs_b); + return diffs; + } + // Perform a real diff. + if (checklines && (text1.length() < 100 || text2.length() < 100)) { + checklines = false; // Too trivial for the overhead. + } + List linearray = null; + if (checklines) { + // Scan the text on a line-by-line basis first. + LinesToCharsResult b = diff_linesToChars(text1, text2); + text1 = b.chars1; + text2 = b.chars2; + linearray = b.lineArray; + } + diffs = diff_map(text1, text2); + if (diffs == null) { + // No acceptable result. + diffs = new LinkedList(); + diffs.add(new Diff(Operation.DELETE, text1)); + diffs.add(new Diff(Operation.INSERT, text2)); + } + if (checklines) { + // Convert the diff back to original text. + diff_charsToLines(diffs, linearray); + // Eliminate freak matches (e.g. blank lines) + diff_cleanupSemantic(diffs); + // Rediff any replacement blocks, this time character-by-character. + // Add a dummy entry at the end. + diffs.add(new Diff(Operation.EQUAL, "")); + int count_delete = 0; + int count_insert = 0; + String text_delete = ""; + String text_insert = ""; + ListIterator pointer = diffs.listIterator(); + Diff thisDiff = pointer.next(); + while (thisDiff != null) { + switch (thisDiff.operation) { + case INSERT: + count_insert++; + text_insert += thisDiff.text; + break; + case DELETE: + count_delete++; + text_delete += thisDiff.text; + break; + case EQUAL: + // Upon reaching an equality, check for prior redundancies. + if (count_delete >= 1 && count_insert >= 1) { + // Delete the offending records and add the merged ones. + pointer.previous(); + for (int j = 0; j < count_delete + count_insert; j++) { + pointer.previous(); + pointer.remove(); + } + for (Diff newDiff : diff_main(text_delete, text_insert, false)) { + pointer.add(newDiff); + } + } + count_insert = 0; + count_delete = 0; + text_delete = ""; + text_insert = ""; + break; + } + thisDiff = pointer.hasNext() ? pointer.next() : null; + } + diffs.removeLast(); // Remove the dummy entry at the end. + } + return diffs; + } + /** + * Split two texts into a list of strings. Reduce the texts to a string of + * hashes where each Unicode character represents one line. + * @param text1 First string. + * @param text2 Second string. + * @return An object containing the encoded text1, the encoded text2 and + * the List of unique strings. The zeroth element of the List of + * unique strings is intentionally blank. + */ + protected LinesToCharsResult diff_linesToChars(String text1, String text2) { + List lineArray = new ArrayList(); + Map lineHash = new HashMap(); + // e.g. linearray[4] == "Hello\n" + // e.g. linehash.get("Hello\n") == 4 + // "\x00" is a valid character, but various debuggers don't like it. + // So we'll insert a junk entry to avoid generating a null character. + lineArray.add(""); + String chars1 = diff_linesToCharsMunge(text1, lineArray, lineHash); + String chars2 = diff_linesToCharsMunge(text2, lineArray, lineHash); + return new LinesToCharsResult(chars1, chars2, lineArray); + } + /** + * Split a text into a list of strings. Reduce the texts to a string of + * hashes where each Unicode character represents one line. + * @param text String to encode. + * @param lineArray List of unique strings. + * @param lineHash Map of strings to indices. + * @return Encoded string. + */ + private String diff_linesToCharsMunge(String text, List lineArray, + Map lineHash) { + int lineStart = 0; + int lineEnd = -1; + String line; + StringBuilder chars = new StringBuilder(); + // Walk the text, pulling out a substring for each line. + // text.split('\n') would would temporarily double our memory footprint. + // Modifying text would create many large strings to garbage collect. + while (lineEnd < text.length() - 1) { + lineEnd = text.indexOf('\n', lineStart); + if (lineEnd == -1) { + lineEnd = text.length() - 1; + } + line = text.substring(lineStart, lineEnd + 1); + lineStart = lineEnd + 1; + + if (lineHash.containsKey(line)) { + chars.append(String.valueOf((char) (int) lineHash.get(line))); + } else { + lineArray.add(line); + lineHash.put(line, lineArray.size() - 1); + chars.append(String.valueOf((char) (lineArray.size() - 1))); + } + } + return chars.toString(); + } + /** + * Rehydrate the text in a diff from a string of line hashes to real lines of + * text. + * @param diffs LinkedList of Diff objects. + * @param lineArray List of unique strings. + */ + protected void diff_charsToLines(LinkedList diffs, + List lineArray) { + StringBuilder text; + for (Diff diff : diffs) { + text = new StringBuilder(); + for (int y = 0; y < diff.text.length(); y++) { + text.append(lineArray.get(diff.text.charAt(y))); + } + diff.text = text.toString(); + } + } + /** + * Explore the intersection points between the two texts. + * @param text1 Old string to be diffed. + * @param text2 New string to be diffed. + * @return LinkedList of Diff objects or null if no diff available. + */ + protected LinkedList diff_map(String text1, String text2) { + long ms_end = System.currentTimeMillis() + (long) (Diff_Timeout * 1000); + // Cache the text lengths to prevent multiple calls. + int text1_length = text1.length(); + int text2_length = text2.length(); + int max_d = text1_length + text2_length - 1; + boolean doubleEnd = Diff_DualThreshold * 2 < max_d; + List> v_map1 = new ArrayList>(); + List> v_map2 = new ArrayList>(); + Map v1 = new HashMap(); + Map v2 = new HashMap(); + v1.put(1, 0); + v2.put(1, 0); + int x, y; + Long footstep = 0L; // Used to track overlapping paths. + Map footsteps = new HashMap(); + boolean done = false; + // If the total number of characters is odd, then the front path will + // collide with the reverse path. + boolean front = ((text1_length + text2_length) % 2 == 1); + for (int d = 0; d < max_d; d++) { + // Bail out if timeout reached. + if (Diff_Timeout > 0 && System.currentTimeMillis() > ms_end) { + return null; + } + + // Walk the front path one step. + v_map1.add(new HashSet()); // Adds at index 'd'. + for (int k = -d; k <= d; k += 2) { + if (k == -d || k != d && v1.get(k - 1) < v1.get(k + 1)) { + x = v1.get(k + 1); + } else { + x = v1.get(k - 1) + 1; + } + y = x - k; + if (doubleEnd) { + footstep = diff_footprint(x, y); + if (front && (footsteps.containsKey(footstep))) { + done = true; + } + if (!front) { + footsteps.put(footstep, d); + } + } + while (!done && x < text1_length && y < text2_length + && text1.charAt(x) == text2.charAt(y)) { + x++; + y++; + if (doubleEnd) { + footstep = diff_footprint(x, y); + if (front && (footsteps.containsKey(footstep))) { + done = true; + } + if (!front) { + footsteps.put(footstep, d); + } + } + } + v1.put(k, x); + v_map1.get(d).add(diff_footprint(x, y)); + if (x == text1_length && y == text2_length) { + // Reached the end in single-path mode. + return diff_path1(v_map1, text1, text2); + } else if (done) { + // Front path ran over reverse path. + v_map2 = v_map2.subList(0, footsteps.get(footstep) + 1); + LinkedList a = diff_path1(v_map1, text1.substring(0, x), + text2.substring(0, y)); + a.addAll(diff_path2(v_map2, text1.substring(x), text2.substring(y))); + return a; + } + } + if (doubleEnd) { + // Walk the reverse path one step. + v_map2.add(new HashSet()); // Adds at index 'd'. + for (int k = -d; k <= d; k += 2) { + if (k == -d || k != d && v2.get(k - 1) < v2.get(k + 1)) { + x = v2.get(k + 1); + } else { + x = v2.get(k - 1) + 1; + } + y = x - k; + footstep = diff_footprint(text1_length - x, text2_length - y); + if (!front && (footsteps.containsKey(footstep))) { + done = true; + } + if (front) { + footsteps.put(footstep, d); + } + while (!done && x < text1_length && y < text2_length + && text1.charAt(text1_length - x - 1) + == text2.charAt(text2_length - y - 1)) { + x++; + y++; + footstep = diff_footprint(text1_length - x, text2_length - y); + if (!front && (footsteps.containsKey(footstep))) { + done = true; + } + if (front) { + footsteps.put(footstep, d); + } + } + v2.put(k, x); + v_map2.get(d).add(diff_footprint(x, y)); + if (done) { + // Reverse path ran over front path. + v_map1 = v_map1.subList(0, footsteps.get(footstep) + 1); + LinkedList a + = diff_path1(v_map1, text1.substring(0, text1_length - x), + text2.substring(0, text2_length - y)); + a.addAll(diff_path2(v_map2, text1.substring(text1_length - x), + text2.substring(text2_length - y))); + return a; + } + } + } + } + // Number of diffs equals number of characters, no commonality at all. + return null; + } + /** + * Work from the middle back to the start to determine the path. + * @param v_map List of path sets. + * @param text1 Old string fragment to be diffed. + * @param text2 New string fragment to be diffed. + * @return LinkedList of Diff objects. + */ + protected LinkedList diff_path1(List> v_map, + String text1, String text2) { + LinkedList path = new LinkedList(); + int x = text1.length(); + int y = text2.length(); + Operation last_op = null; + for (int d = v_map.size() - 2; d >= 0; d--) { + while (true) { + if (v_map.get(d).contains(diff_footprint(x - 1, y))) { + x--; + if (last_op == Operation.DELETE) { + path.getFirst().text = text1.charAt(x) + path.getFirst().text; + } else { + path.addFirst(new Diff(Operation.DELETE, + text1.substring(x, x + 1))); + } + last_op = Operation.DELETE; + break; + } else if (v_map.get(d).contains(diff_footprint(x, y - 1))) { + y--; + if (last_op == Operation.INSERT) { + path.getFirst().text = text2.charAt(y) + path.getFirst().text; + } else { + path.addFirst(new Diff(Operation.INSERT, + text2.substring(y, y + 1))); + } + last_op = Operation.INSERT; + break; + } else { + x--; + y--; + assert (text1.charAt(x) == text2.charAt(y)) + : "No diagonal. Can't happen. (diff_path1)"; + if (last_op == Operation.EQUAL) { + path.getFirst().text = text1.charAt(x) + path.getFirst().text; + } else { + path.addFirst(new Diff(Operation.EQUAL, text1.substring(x, x + 1))); + } + last_op = Operation.EQUAL; + } + } + } + return path; + } + /** + * Work from the middle back to the end to determine the path. + * @param v_map List of path sets. + * @param text1 Old string fragment to be diffed. + * @param text2 New string fragment to be diffed. + * @return LinkedList of Diff objects. + */ + protected LinkedList diff_path2(List> v_map, + String text1, String text2) { + LinkedList path = new LinkedList(); + int x = text1.length(); + int y = text2.length(); + Operation last_op = null; + for (int d = v_map.size() - 2; d >= 0; d--) { + while (true) { + if (v_map.get(d).contains(diff_footprint(x - 1, y))) { + x--; + if (last_op == Operation.DELETE) { + path.getLast().text += text1.charAt(text1.length() - x - 1); + } else { + path.addLast(new Diff(Operation.DELETE, + text1.substring(text1.length() - x - 1, text1.length() - x))); + } + last_op = Operation.DELETE; + break; + } else if (v_map.get(d).contains(diff_footprint(x, y - 1))) { + y--; + if (last_op == Operation.INSERT) { + path.getLast().text += text2.charAt(text2.length() - y - 1); + } else { + path.addLast(new Diff(Operation.INSERT, + text2.substring(text2.length() - y - 1, text2.length() - y))); + } + last_op = Operation.INSERT; + break; + } else { + x--; + y--; + assert (text1.charAt(text1.length() - x - 1) + == text2.charAt(text2.length() - y - 1)) + : "No diagonal. Can't happen. (diff_path2)"; + if (last_op == Operation.EQUAL) { + path.getLast().text += text1.charAt(text1.length() - x - 1); + } else { + path.addLast(new Diff(Operation.EQUAL, + text1.substring(text1.length() - x - 1, text1.length() - x))); + } + last_op = Operation.EQUAL; + } + } + } + return path; + } + /** + * Compute a good hash of two integers. + * @param x First int. + * @param y Second int. + * @return A long made up of both ints. + */ + protected long diff_footprint(int x, int y) { + // The maximum size for a long is 9,223,372,036,854,775,807 + // The maximum size for an int is 2,147,483,647 + // Two ints fit nicely in one long. + long result = x; + result = result << 32; + result += y; + return result; + } + /** + * Determine the common prefix of two strings + * @param text1 First string. + * @param text2 Second string. + * @return The number of characters common to the start of each string. + */ + public int diff_commonPrefix(String text1, String text2) { + // Performance analysis: http://neil.fraser.name/news/2007/10/09/ + int n = Math.min(text1.length(), text2.length()); + for (int i = 0; i < n; i++) { + if (text1.charAt(i) != text2.charAt(i)) { + return i; + } + } + return n; + } + /** + * Determine the common suffix of two strings + * @param text1 First string. + * @param text2 Second string. + * @return The number of characters common to the end of each string. + */ + public int diff_commonSuffix(String text1, String text2) { + // Performance analysis: http://neil.fraser.name/news/2007/10/09/ + int text1_length = text1.length(); + int text2_length = text2.length(); + int n = Math.min(text1_length, text2_length); + for (int i = 1; i <= n; i++) { + if (text1.charAt(text1_length - i) != text2.charAt(text2_length - i)) { + return i - 1; + } + } + return n; + } + /** + * Do the two texts share a substring which is at least half the length of + * the longer text? + * @param text1 First string. + * @param text2 Second string. + * @return Five element String array, containing the prefix of text1, the + * suffix of text1, the prefix of text2, the suffix of text2 and the + * common middle. Or null if there was no match. + */ + protected String[] diff_halfMatch(String text1, String text2) { + String longtext = text1.length() > text2.length() ? text1 : text2; + String shorttext = text1.length() > text2.length() ? text2 : text1; + if (longtext.length() < 10 || shorttext.length() < 1) { + return null; // Pointless. + } + + // First check if the second quarter is the seed for a half-match. + String[] hm1 = diff_halfMatchI(longtext, shorttext, + (longtext.length() + 3) / 4); + // Check again based on the third quarter. + String[] hm2 = diff_halfMatchI(longtext, shorttext, + (longtext.length() + 1) / 2); + String[] hm; + if (hm1 == null && hm2 == null) { + return null; + } else if (hm2 == null) { + hm = hm1; + } else if (hm1 == null) { + hm = hm2; + } else { + // Both matched. Select the longest. + hm = hm1[4].length() > hm2[4].length() ? hm1 : hm2; + } + // A half-match was found, sort out the return data. + if (text1.length() > text2.length()) { + return hm; + //return new String[]{hm[0], hm[1], hm[2], hm[3], hm[4]}; + } else { + return new String[]{hm[2], hm[3], hm[0], hm[1], hm[4]}; + } + } + /** + * Does a substring of shorttext exist within longtext such that the + * substring is at least half the length of longtext? + * @param longtext Longer string. + * @param shorttext Shorter string. + * @param i Start index of quarter length substring within longtext. + * @return Five element String array, containing the prefix of longtext, the + * suffix of longtext, the prefix of shorttext, the suffix of shorttext + * and the common middle. Or null if there was no match. + */ + private String[] diff_halfMatchI(String longtext, String shorttext, int i) { + // Start with a 1/4 length substring at position i as a seed. + String seed = longtext.substring(i, i + longtext.length() / 4); + int j = -1; + String best_common = ""; + String best_longtext_a = "", best_longtext_b = ""; + String best_shorttext_a = "", best_shorttext_b = ""; + while ((j = shorttext.indexOf(seed, j + 1)) != -1) { + int prefixLength = diff_commonPrefix(longtext.substring(i), shorttext.substring(j)); + int suffixLength = diff_commonSuffix(longtext.substring(0, i), + shorttext.substring(0, j)); + if (best_common.length() < suffixLength + prefixLength) { + best_common = shorttext.substring(j - suffixLength, j) + + shorttext.substring(j, j + prefixLength); + best_longtext_a = longtext.substring(0, i - suffixLength); + best_longtext_b = longtext.substring(i + prefixLength); + best_shorttext_a = shorttext.substring(0, j - suffixLength); + best_shorttext_b = shorttext.substring(j + prefixLength); + } + } + if (best_common.length() >= longtext.length() / 2) { + return new String[]{best_longtext_a, best_longtext_b, + best_shorttext_a, best_shorttext_b, best_common}; + } else { + return null; + } + } + /** + * Reduce the number of edits by eliminating semantically trivial equalities. + * @param diffs LinkedList of Diff objects. + */ + public void diff_cleanupSemantic(LinkedList diffs) { + if (diffs.isEmpty()) { + return; + } + boolean changes = false; + Stack equalities = new Stack(); // Stack of qualities. + String lastequality = null; // Always equal to equalities.lastElement().text + ListIterator pointer = diffs.listIterator(); + // Number of characters that changed prior to the equality. + int length_changes1 = 0; + // Number of characters that changed after the equality. + int length_changes2 = 0; + Diff thisDiff = pointer.next(); + while (thisDiff != null) { + if (thisDiff.operation == Operation.EQUAL) { + // equality found + equalities.push(thisDiff); + length_changes1 = length_changes2; + length_changes2 = 0; + lastequality = thisDiff.text; + } else { + // an insertion or deletion + length_changes2 += thisDiff.text.length(); + if (lastequality != null && (lastequality.length() <= length_changes1) + && (lastequality.length() <= length_changes2)) { + //System.out.println("Splitting: '" + lastequality + "'"); + // Walk back to offending equality. + while (thisDiff != equalities.lastElement()) { + thisDiff = pointer.previous(); + } + pointer.next(); + // Replace equality with a delete. + pointer.set(new Diff(Operation.DELETE, lastequality)); + // Insert a corresponding an insert. + pointer.add(new Diff(Operation.INSERT, lastequality)); + + equalities.pop(); // Throw away the equality we just deleted. + if (!equalities.empty()) { + // Throw away the previous equality (it needs to be reevaluated). + equalities.pop(); + } + if (equalities.empty()) { + // There are no previous equalities, walk back to the start. + while (pointer.hasPrevious()) { + pointer.previous(); + } + } else { + // There is a safe equality we can fall back to. + thisDiff = equalities.lastElement(); + while (thisDiff != pointer.previous()) { + // Intentionally empty loop. + } + } + length_changes1 = 0; // Reset the counters. + length_changes2 = 0; + lastequality = null; + changes = true; + } + } + thisDiff = pointer.hasNext() ? pointer.next() : null; + } + if (changes) { + diff_cleanupMerge(diffs); + } + diff_cleanupSemanticLossless(diffs); + } + /** + * Look for single edits surrounded on both sides by equalities + * which can be shifted sideways to align the edit to a word boundary. + * e.g: The cat came. -> The cat came. + * @param diffs LinkedList of Diff objects. + */ + public void diff_cleanupSemanticLossless(LinkedList diffs) { + String equality1, edit, equality2; + String commonString; + int commonOffset; + int score, bestScore; + String bestEquality1, bestEdit, bestEquality2; + // Create a new iterator at the start. + ListIterator pointer = diffs.listIterator(); + Diff prevDiff = pointer.hasNext() ? pointer.next() : null; + Diff thisDiff = pointer.hasNext() ? pointer.next() : null; + Diff nextDiff = pointer.hasNext() ? pointer.next() : null; + // Intentionally ignore the first and last element (don't need checking). + while (nextDiff != null) { + if (prevDiff.operation == Operation.EQUAL && + nextDiff.operation == Operation.EQUAL) { + // This is a single edit surrounded by equalities. + equality1 = prevDiff.text; + edit = thisDiff.text; + equality2 = nextDiff.text; + + // First, shift the edit as far left as possible. + commonOffset = diff_commonSuffix(equality1, edit); + if (commonOffset != 0) { + commonString = edit.substring(edit.length() - commonOffset); + equality1 = equality1.substring(0, equality1.length() - commonOffset); + edit = commonString + edit.substring(0, edit.length() - commonOffset); + equality2 = commonString + equality2; + } + // Second, step character by character right, looking for the best fit. + bestEquality1 = equality1; + bestEdit = edit; + bestEquality2 = equality2; + bestScore = diff_cleanupSemanticScore(equality1, edit) + + diff_cleanupSemanticScore(edit, equality2); + while (edit.length() != 0 && equality2.length() != 0 + && edit.charAt(0) == equality2.charAt(0)) { + equality1 += edit.charAt(0); + edit = edit.substring(1) + equality2.charAt(0); + equality2 = equality2.substring(1); + score = diff_cleanupSemanticScore(equality1, edit) + + diff_cleanupSemanticScore(edit, equality2); + // The >= encourages trailing rather than leading whitespace on edits. + if (score >= bestScore) { + bestScore = score; + bestEquality1 = equality1; + bestEdit = edit; + bestEquality2 = equality2; + } + } + + if (!prevDiff.text.equals(bestEquality1)) { + // We have an improvement, save it back to the diff. + if (bestEquality1.length() != 0) { + prevDiff.text = bestEquality1; + } else { + pointer.previous(); // Walk past nextDiff. + pointer.previous(); // Walk past thisDiff. + pointer.previous(); // Walk past prevDiff. + pointer.remove(); // Delete prevDiff. + pointer.next(); // Walk past thisDiff. + pointer.next(); // Walk past nextDiff. + } + thisDiff.text = bestEdit; + if (bestEquality2.length() != 0) { + nextDiff.text = bestEquality2; + } else { + pointer.remove(); // Delete nextDiff. + nextDiff = thisDiff; + thisDiff = prevDiff; + } + } + } + prevDiff = thisDiff; + thisDiff = nextDiff; + nextDiff = pointer.hasNext() ? pointer.next() : null; + } + } + /** + * Given two strings, compute a score representing whether the internal + * boundary falls on logical boundaries. + * Scores range from 5 (best) to 0 (worst). + * @param one First string. + * @param two Second string. + * @return The score. + */ + private int diff_cleanupSemanticScore(String one, String two) { + if (one.length() == 0 || two.length() == 0) { + // Edges are the best. + return 5; + } + // Each port of this function behaves slightly differently due to + // subtle differences in each language's definition of things like + // 'whitespace'. Since this function's purpose is largely cosmetic, + // the choice has been made to use each language's native features + // rather than force total conformity. + int score = 0; + // One point for non-alphanumeric. + if (!Character.isLetterOrDigit(one.charAt(one.length() - 1)) + || !Character.isLetterOrDigit(two.charAt(0))) { + score++; + // Two points for whitespace. + if (Character.isWhitespace(one.charAt(one.length() - 1)) + || Character.isWhitespace(two.charAt(0))) { + score++; + // Three points for line breaks. + if (Character.getType(one.charAt(one.length() - 1)) == Character.CONTROL + || Character.getType(two.charAt(0)) == Character.CONTROL) { + score++; + // Four points for blank lines. + if (BLANKLINEEND.matcher(one).find() + || BLANKLINESTART.matcher(two).find()) { + score++; + } + } + } + } + return score; + } + private Pattern BLANKLINEEND + = Pattern.compile("\\n\\r?\\n\\Z", Pattern.DOTALL); + private Pattern BLANKLINESTART + = Pattern.compile("\\A\\r?\\n\\r?\\n", Pattern.DOTALL); + /** + * Reduce the number of edits by eliminating operationally trivial equalities. + * @param diffs LinkedList of Diff objects. + */ + public void diff_cleanupEfficiency(LinkedList diffs) { + if (diffs.isEmpty()) { + return; + } + boolean changes = false; + Stack equalities = new Stack(); // Stack of equalities. + String lastequality = null; // Always equal to equalities.lastElement().text + ListIterator pointer = diffs.listIterator(); + // Is there an insertion operation before the last equality. + boolean pre_ins = false; + // Is there a deletion operation before the last equality. + boolean pre_del = false; + // Is there an insertion operation after the last equality. + boolean post_ins = false; + // Is there a deletion operation after the last equality. + boolean post_del = false; + Diff thisDiff = pointer.next(); + Diff safeDiff = thisDiff; // The last Diff that is known to be unsplitable. + while (thisDiff != null) { + if (thisDiff.operation == Operation.EQUAL) { + // equality found + if (thisDiff.text.length() < Diff_EditCost && (post_ins || post_del)) { + // Candidate found. + equalities.push(thisDiff); + pre_ins = post_ins; + pre_del = post_del; + lastequality = thisDiff.text; + } else { + // Not a candidate, and can never become one. + equalities.clear(); + lastequality = null; + safeDiff = thisDiff; + } + post_ins = post_del = false; + } else { + // an insertion or deletion + if (thisDiff.operation == Operation.DELETE) { + post_del = true; + } else { + post_ins = true; + } + /* + * Five types to be split: + * ABXYCD + * AXCD + * ABXC + * AXCD + * ABXC + */ + if (lastequality != null + && ((pre_ins && pre_del && post_ins && post_del) + || ((lastequality.length() < Diff_EditCost / 2) + && ((pre_ins ? 1 : 0) + (pre_del ? 1 : 0) + + (post_ins ? 1 : 0) + (post_del ? 1 : 0)) == 3))) { + //System.out.println("Splitting: '" + lastequality + "'"); + // Walk back to offending equality. + while (thisDiff != equalities.lastElement()) { + thisDiff = pointer.previous(); + } + pointer.next(); + + // Replace equality with a delete. + pointer.set(new Diff(Operation.DELETE, lastequality)); + // Insert a corresponding an insert. + pointer.add(thisDiff = new Diff(Operation.INSERT, lastequality)); + + equalities.pop(); // Throw away the equality we just deleted. + lastequality = null; + if (pre_ins && pre_del) { + // No changes made which could affect previous entry, keep going. + post_ins = post_del = true; + equalities.clear(); + safeDiff = thisDiff; + } else { + if (!equalities.empty()) { + // Throw away the previous equality (it needs to be reevaluated). + equalities.pop(); + } + if (equalities.empty()) { + // There are no previous questionable equalities, + // walk back to the last known safe diff. + thisDiff = safeDiff; + } else { + // There is an equality we can fall back to. + thisDiff = equalities.lastElement(); + } + while (thisDiff != pointer.previous()) { + // Intentionally empty loop. + } + post_ins = post_del = false; + } + changes = true; + } + } + thisDiff = pointer.hasNext() ? pointer.next() : null; + } + if (changes) { + diff_cleanupMerge(diffs); + } + } + /** + * Reorder and merge like edit sections. Merge equalities. + * Any edit section can move as long as it doesn't cross an equality. + * @param diffs LinkedList of Diff objects. + */ + public void diff_cleanupMerge(LinkedList diffs) { + diffs.add(new Diff(Operation.EQUAL, "")); // Add a dummy entry at the end. + ListIterator pointer = diffs.listIterator(); + int count_delete = 0; + int count_insert = 0; + String text_delete = ""; + String text_insert = ""; + Diff thisDiff = pointer.next(); + Diff prevEqual = null; + int commonlength; + while (thisDiff != null) { + switch (thisDiff.operation) { + case INSERT: + count_insert++; + text_insert += thisDiff.text; + prevEqual = null; + break; + case DELETE: + count_delete++; + text_delete += thisDiff.text; + prevEqual = null; + break; + case EQUAL: + if (count_delete != 0 || count_insert != 0) { + // Delete the offending records. + pointer.previous(); // Reverse direction. + while (count_delete-- > 0) { + pointer.previous(); + pointer.remove(); + } + while (count_insert-- > 0) { + pointer.previous(); + pointer.remove(); + } + if (count_delete != 0 && count_insert != 0) { + // Factor out any common prefixies. + commonlength = diff_commonPrefix(text_insert, text_delete); + if (commonlength != 0) { + if (pointer.hasPrevious()) { + thisDiff = pointer.previous(); + assert thisDiff.operation == Operation.EQUAL + : "Previous diff should have been an equality."; + thisDiff.text += text_insert.substring(0, commonlength); + pointer.next(); + } else { + pointer.add(new Diff(Operation.EQUAL, + text_insert.substring(0, commonlength))); + } + text_insert = text_insert.substring(commonlength); + text_delete = text_delete.substring(commonlength); + } + // Factor out any common suffixies. + commonlength = diff_commonSuffix(text_insert, text_delete); + if (commonlength != 0) { + thisDiff = pointer.next(); + thisDiff.text = text_insert.substring(text_insert.length() + - commonlength) + thisDiff.text; + text_insert = text_insert.substring(0, text_insert.length() + - commonlength); + text_delete = text_delete.substring(0, text_delete.length() + - commonlength); + pointer.previous(); + } + } + // Insert the merged records. + if (text_delete.length() != 0) { + pointer.add(new Diff(Operation.DELETE, text_delete)); + } + if (text_insert.length() != 0) { + pointer.add(new Diff(Operation.INSERT, text_insert)); + } + // Step forward to the equality. + thisDiff = pointer.hasNext() ? pointer.next() : null; + } else if (prevEqual != null) { + // Merge this equality with the previous one. + prevEqual.text += thisDiff.text; + pointer.remove(); + thisDiff = pointer.previous(); + pointer.next(); // Forward direction + } + count_insert = 0; + count_delete = 0; + text_delete = ""; + text_insert = ""; + prevEqual = thisDiff; + break; + } + thisDiff = pointer.hasNext() ? pointer.next() : null; + } + // System.out.println(diff); + if (diffs.getLast().text.length() == 0) { + diffs.removeLast(); // Remove the dummy entry at the end. + } + /* + * Second pass: look for single edits surrounded on both sides by equalities + * which can be shifted sideways to eliminate an equality. + * e.g: ABAC -> ABAC + */ + boolean changes = false; + // Create a new iterator at the start. + // (As opposed to walking the current one back.) + pointer = diffs.listIterator(); + Diff prevDiff = pointer.hasNext() ? pointer.next() : null; + thisDiff = pointer.hasNext() ? pointer.next() : null; + Diff nextDiff = pointer.hasNext() ? pointer.next() : null; + // Intentionally ignore the first and last element (don't need checking). + while (nextDiff != null) { + if (prevDiff.operation == Operation.EQUAL && + nextDiff.operation == Operation.EQUAL) { + // This is a single edit surrounded by equalities. + if (thisDiff.text.endsWith(prevDiff.text)) { + // Shift the edit over the previous equality. + thisDiff.text = prevDiff.text + thisDiff.text.substring(0, thisDiff.text.length() - prevDiff.text.length()); + nextDiff.text = prevDiff.text + nextDiff.text; + pointer.previous(); // Walk past nextDiff. + pointer.previous(); // Walk past thisDiff. + pointer.previous(); // Walk past prevDiff. + pointer.remove(); // Delete prevDiff. + pointer.next(); // Walk past thisDiff. + thisDiff = pointer.next(); // Walk past nextDiff. + nextDiff = pointer.hasNext() ? pointer.next() : null; + changes = true; + } else if (thisDiff.text.startsWith(nextDiff.text)) { + // Shift the edit over the next equality. + prevDiff.text += nextDiff.text; + thisDiff.text = thisDiff.text.substring(nextDiff.text.length()) + + nextDiff.text; + pointer.remove(); // Delete nextDiff. + nextDiff = pointer.hasNext() ? pointer.next() : null; + changes = true; + } + } + prevDiff = thisDiff; + thisDiff = nextDiff; + nextDiff = pointer.hasNext() ? pointer.next() : null; + } + // If shifts were made, the diff needs reordering and another shift sweep. + if (changes) { + diff_cleanupMerge(diffs); + } + } + /** + * loc is a location in text1, compute and return the equivalent location in + * text2. + * e.g. "The cat" vs "The big cat", 1->1, 5->8 + * @param diffs LinkedList of Diff objects. + * @param loc Location within text1. + * @return Location within text2. + */ + public int diff_xIndex(LinkedList diffs, int loc) { + int chars1 = 0; + int chars2 = 0; + int last_chars1 = 0; + int last_chars2 = 0; + Diff lastDiff = null; + for (Diff aDiff : diffs) { + if (aDiff.operation != Operation.INSERT) { + // Equality or deletion. + chars1 += aDiff.text.length(); + } + if (aDiff.operation != Operation.DELETE) { + // Equality or insertion. + chars2 += aDiff.text.length(); + } + if (chars1 > loc) { + // Overshot the location. + lastDiff = aDiff; + break; + } + last_chars1 = chars1; + last_chars2 = chars2; + } + if (lastDiff != null && lastDiff.operation == Operation.DELETE) { + // The location was deleted. + return last_chars2; + } + // Add the remaining character length. + return last_chars2 + (loc - last_chars1); + } + /** + * Convert a Diff list into a pretty HTML report. + * @param diffs LinkedList of Diff objects. + * @return HTML representation. + */ + public String diff_prettyHtml(LinkedList diffs) { + StringBuilder html = new StringBuilder(); + int i = 0; + for (Diff aDiff : diffs) { + String text = aDiff.text.replace("&", "&").replace("<", "<") + .replace(">", ">").replace("\n", "¶
    "); + switch (aDiff.operation) { + case INSERT: + html.append("").append(text).append(""); + break; + case DELETE: + html.append("").append(text).append(""); + break; + case EQUAL: + html.append("").append(text) + .append(""); + break; + } + if (aDiff.operation != Operation.DELETE) { + i += aDiff.text.length(); + } + } + return html.toString(); + } + /** + * Compute and return the source text (all equalities and deletions). + * @param diffs LinkedList of Diff objects. + * @return Source text. + */ + public String diff_text1(LinkedList diffs) { + StringBuilder text = new StringBuilder(); + for (Diff aDiff : diffs) { + if (aDiff.operation != Operation.INSERT) { + text.append(aDiff.text); + } + } + return text.toString(); + } + /** + * Compute and return the destination text (all equalities and insertions). + * @param diffs LinkedList of Diff objects. + * @return Destination text. + */ + public String diff_text2(LinkedList diffs) { + StringBuilder text = new StringBuilder(); + for (Diff aDiff : diffs) { + if (aDiff.operation != Operation.DELETE) { + text.append(aDiff.text); + } + } + return text.toString(); + } + /** + * Compute the Levenshtein distance; the number of inserted, deleted or + * substituted characters. + * @param diffs LinkedList of Diff objects. + * @return Number of changes. + */ + public int diff_levenshtein(LinkedList diffs) { + int levenshtein = 0; + int insertions = 0; + int deletions = 0; + for (Diff aDiff : diffs) { + switch (aDiff.operation) { + case INSERT: + insertions += aDiff.text.length(); + break; + case DELETE: + deletions += aDiff.text.length(); + break; + case EQUAL: + // A deletion and an insertion is one substitution. + levenshtein += Math.max(insertions, deletions); + insertions = 0; + deletions = 0; + break; + } + } + levenshtein += Math.max(insertions, deletions); + return levenshtein; + } + /** + * Crush the diff into an encoded string which describes the operations + * required to transform text1 into text2. + * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. + * Operations are tab-separated. Inserted text is escaped using %xx notation. + * @param diffs Array of diff tuples. + * @return Delta text. + */ + public String diff_toDelta(LinkedList diffs) { + StringBuilder text = new StringBuilder(); + for (Diff aDiff : diffs) { + switch (aDiff.operation) { + case INSERT: + try { + text.append("+").append(URLEncoder.encode(aDiff.text, "UTF-8") + .replace('+', ' ')).append("\t"); + } catch (UnsupportedEncodingException e) { + // Not likely on modern system. + throw new Error("This system does not support UTF-8.", e); + } + break; + case DELETE: + text.append("-").append(aDiff.text.length()).append("\t"); + break; + case EQUAL: + text.append("=").append(aDiff.text.length()).append("\t"); + break; + } + } + String delta = text.toString(); + if (delta.length() != 0) { + // Strip off trailing tab character. + delta = delta.substring(0, delta.length() - 1); + delta = unescapeForEncodeUriCompatability(delta); + } + return delta; + } + /** + * Given the original text1, and an encoded string which describes the + * operations required to transform text1 into text2, compute the full diff. + * @param text1 Source string for the diff. + * @param delta Delta text. + * @return Array of diff tuples or null if invalid. + * @throws IllegalArgumentException If invalid input. + */ + public LinkedList diff_fromDelta(String text1, String delta) + throws IllegalArgumentException { + LinkedList diffs = new LinkedList(); + int pointer = 0; // Cursor in text1 + String[] tokens = delta.split("\t"); + for (String token : tokens) { + if (token.length() == 0) { + // Blank tokens are ok (from a trailing \t). + continue; + } + // Each token begins with a one character parameter which specifies the + // operation of this token (delete, insert, equality). + String param = token.substring(1); + switch (token.charAt(0)) { + case '+': + // decode would change all "+" to " " + param = param.replace("+", "%2B"); + try { + param = URLDecoder.decode(param, "UTF-8"); + } catch (UnsupportedEncodingException e) { + // Not likely on modern system. + throw new Error("This system does not support UTF-8.", e); + } catch (IllegalArgumentException e) { + // Malformed URI sequence. + throw new IllegalArgumentException( + "Illegal escape in diff_fromDelta: " + param, e); + } + diffs.add(new Diff(Operation.INSERT, param)); + break; + case '-': + // Fall through. + case '=': + int n; + try { + n = Integer.parseInt(param); + } catch (NumberFormatException e) { + throw new IllegalArgumentException( + "Invalid number in diff_fromDelta: " + param, e); + } + if (n < 0) { + throw new IllegalArgumentException( + "Negative number in diff_fromDelta: " + param); + } + String text; + try { + text = text1.substring(pointer, pointer += n); + } catch (StringIndexOutOfBoundsException e) { + throw new IllegalArgumentException("Delta length (" + pointer + + ") larger than source text length (" + text1.length() + + ").", e); + } + if (token.charAt(0) == '=') { + diffs.add(new Diff(Operation.EQUAL, text)); + } else { + diffs.add(new Diff(Operation.DELETE, text)); + } + break; + default: + // Anything else is an error. + throw new IllegalArgumentException( + "Invalid diff operation in diff_fromDelta: " + token.charAt(0)); + } + } + if (pointer != text1.length()) { + throw new IllegalArgumentException("Delta length (" + pointer + + ") smaller than source text length (" + text1.length() + ")."); + } + return diffs; + } + // MATCH FUNCTIONS + /** + * Locate the best instance of 'pattern' in 'text' near 'loc'. + * Returns -1 if no match found. + * @param text The text to search. + * @param pattern The pattern to search for. + * @param loc The location to search around. + * @return Best match index or -1. + */ + public int match_main(String text, String pattern, int loc) { + loc = Math.max(0, Math.min(loc, text.length())); + if (text.equals(pattern)) { + // Shortcut (potentially not guaranteed by the algorithm) + return 0; + } else if (text.length() == 0) { + // Nothing to match. + return -1; + } else if (loc + pattern.length() <= text.length() + && text.substring(loc, loc + pattern.length()).equals(pattern)) { + // Perfect match at the perfect spot! (Includes case of null pattern) + return loc; + } else { + // Do a fuzzy compare. + return match_bitap(text, pattern, loc); + } + } + /** + * Locate the best instance of 'pattern' in 'text' near 'loc' using the + * Bitap algorithm. Returns -1 if no match found. + * @param text The text to search. + * @param pattern The pattern to search for. + * @param loc The location to search around. + * @return Best match index or -1. + */ + protected int match_bitap(String text, String pattern, int loc) { + assert (Match_MaxBits == 0 || pattern.length() <= Match_MaxBits) + : "Pattern too long for this application."; + // Initialise the alphabet. + Map s = match_alphabet(pattern); + // Highest score beyond which we give up. + double score_threshold = Match_Threshold; + // Is there a nearby exact match? (speedup) + int best_loc = text.indexOf(pattern, loc); + if (best_loc != -1) { + score_threshold = Math.min(match_bitapScore(0, best_loc, loc, pattern), + score_threshold); + // What about in the other direction? (speedup) + best_loc = text.lastIndexOf(pattern, loc + pattern.length()); + if (best_loc != -1) { + score_threshold = Math.min(match_bitapScore(0, best_loc, loc, pattern), + score_threshold); + } + } + // Initialise the bit arrays. + int matchmask = 1 << (pattern.length() - 1); + best_loc = -1; + int bin_min, bin_mid; + int bin_max = pattern.length() + text.length(); + // Empty initialization added to appease Java compiler. + int[] last_rd = new int[0]; + for (int d = 0; d < pattern.length(); d++) { + // Scan for the best match; each iteration allows for one more error. + // Run a binary search to determine how far from 'loc' we can stray at + // this error level. + bin_min = 0; + bin_mid = bin_max; + while (bin_min < bin_mid) { + if (match_bitapScore(d, loc + bin_mid, loc, pattern) + <= score_threshold) { + bin_min = bin_mid; + } else { + bin_max = bin_mid; + } + bin_mid = (bin_max - bin_min) / 2 + bin_min; + } + // Use the result from this iteration as the maximum for the next. + bin_max = bin_mid; + int start = Math.max(1, loc - bin_mid + 1); + int finish = Math.min(loc + bin_mid, text.length()) + pattern.length(); + int[] rd = new int[finish + 2]; + rd[finish + 1] = (1 << d) - 1; + for (int j = finish; j >= start; j--) { + int charMatch; + if (text.length() <= j - 1 || !s.containsKey(text.charAt(j - 1))) { + // Out of range. + charMatch = 0; + } else { + charMatch = s.get(text.charAt(j - 1)); + } + if (d == 0) { + // First pass: exact match. + rd[j] = ((rd[j + 1] << 1) | 1) & charMatch; + } else { + // Subsequent passes: fuzzy match. + rd[j] = ((rd[j + 1] << 1) | 1) & charMatch + | (((last_rd[j + 1] | last_rd[j]) << 1) | 1) | last_rd[j + 1]; + } + if ((rd[j] & matchmask) != 0) { + double score = match_bitapScore(d, j - 1, loc, pattern); + // This match will almost certainly be better than any existing + // match. But check anyway. + if (score <= score_threshold) { + // Told you so. + score_threshold = score; + best_loc = j - 1; + if (best_loc > loc) { + // When passing loc, don't exceed our current distance from loc. + start = Math.max(1, 2 * loc - best_loc); + } else { + // Already passed loc, downhill from here on in. + break; + } + } + } + } + if (match_bitapScore(d + 1, loc, loc, pattern) > score_threshold) { + // No hope for a (better) match at greater error levels. + break; + } + last_rd = rd; + } + return best_loc; + } + /** + * Compute and return the score for a match with e errors and x location. + * @param e Number of errors in match. + * @param x Location of match. + * @param loc Expected location of match. + * @param pattern Pattern being sought. + * @return Overall score for match (0.0 = good, 1.0 = bad). + */ + private double match_bitapScore(int e, int x, int loc, String pattern) { + float accuracy = (float) e / pattern.length(); + int proximity = Math.abs(loc - x); + if (Match_Distance == 0) { + // Dodge divide by zero error. + return proximity == 0 ? accuracy : 1.0; + } + return accuracy + (proximity / (float) Match_Distance); + } + /** + * Initialise the alphabet for the Bitap algorithm. + * @param pattern The text to encode. + * @return Hash of character locations. + */ + protected Map match_alphabet(String pattern) { + Map s = new HashMap(); + char[] char_pattern = pattern.toCharArray(); + for (char c : char_pattern) { + s.put(c, 0); + } + int i = 0; + for (char c : char_pattern) { + s.put(c, s.get(c) | (1 << (pattern.length() - i - 1))); + i++; + } + return s; + } + // PATCH FUNCTIONS + /** + * Increase the context until it is unique, + * but don't let the pattern expand beyond Match_MaxBits. + * @param patch The patch to grow. + * @param text Source text. + */ + protected void patch_addContext(Patch patch, String text) { + if (text.length() == 0) { + return; + } + String pattern = text.substring(patch.start2, patch.start2 + patch.length1); + int padding = 0; + // Look for the first and last matches of pattern in text. If two different + // matches are found, increase the pattern length. + while (text.indexOf(pattern) != text.lastIndexOf(pattern) + && pattern.length() < Match_MaxBits - Patch_Margin - Patch_Margin) { + padding += Patch_Margin; + pattern = text.substring(Math.max(0, patch.start2 - padding), + Math.min(text.length(), patch.start2 + patch.length1 + padding)); + } + // Add one chunk for good luck. + padding += Patch_Margin; + // Add the prefix. + String prefix = text.substring(Math.max(0, patch.start2 - padding), + patch.start2); + if (prefix.length() != 0) { + patch.diffs.addFirst(new Diff(Operation.EQUAL, prefix)); + } + // Add the suffix. + String suffix = text.substring(patch.start2 + patch.length1, + Math.min(text.length(), patch.start2 + patch.length1 + padding)); + if (suffix.length() != 0) { + patch.diffs.addLast(new Diff(Operation.EQUAL, suffix)); + } + // Roll back the start points. + patch.start1 -= prefix.length(); + patch.start2 -= prefix.length(); + // Extend the lengths. + patch.length1 += prefix.length() + suffix.length(); + patch.length2 += prefix.length() + suffix.length(); + } + /** + * Compute a list of patches to turn text1 into text2. + * A set of diffs will be computed. + * @param text1 Old text. + * @param text2 New text. + * @return LinkedList of Patch objects. + */ + public LinkedList patch_make(String text1, String text2) { + // No diffs provided, compute our own. + LinkedList diffs = diff_main(text1, text2, true); + if (diffs.size() > 2) { + diff_cleanupSemantic(diffs); + diff_cleanupEfficiency(diffs); + } + return patch_make(text1, diffs); + } + /** + * Compute a list of patches to turn text1 into text2. + * text1 will be derived from the provided diffs. + * @param diffs Array of diff tuples for text1 to text2. + * @return LinkedList of Patch objects. + */ + public LinkedList patch_make(LinkedList diffs) { + // No origin string provided, compute our own. + String text1 = diff_text1(diffs); + return patch_make(text1, diffs); + } + /** + * Compute a list of patches to turn text1 into text2. + * text2 is ignored, diffs are the delta between text1 and text2. + * @param text1 Old text + * @param text2 Ignored. + * @param diffs Array of diff tuples for text1 to text2. + * @return LinkedList of Patch objects. + * @deprecated Prefer patch_make(String text1, LinkedList diffs). + */ + public LinkedList patch_make(String text1, String text2, + LinkedList diffs) { + return patch_make(text1, diffs); + } + /** + * Compute a list of patches to turn text1 into text2. + * text2 is not provided, diffs are the delta between text1 and text2. + * @param text1 Old text. + * @param diffs Array of diff tuples for text1 to text2. + * @return LinkedList of Patch objects. + */ + public LinkedList patch_make(String text1, LinkedList diffs) { + LinkedList patches = new LinkedList(); + if (diffs.isEmpty()) { + return patches; // Get rid of the null case. + } + Patch patch = new Patch(); + int char_count1 = 0; // Number of characters into the text1 string. + int char_count2 = 0; // Number of characters into the text2 string. + // Start with text1 (prepatch_text) and apply the diffs until we arrive at + // text2 (postpatch_text). We recreate the patches one by one to determine + // context info. + String prepatch_text = text1; + String postpatch_text = text1; + for (Diff aDiff : diffs) { + if (patch.diffs.isEmpty() && aDiff.operation != Operation.EQUAL) { + // A new patch starts here. + patch.start1 = char_count1; + patch.start2 = char_count2; + } + switch (aDiff.operation) { + case INSERT: + patch.diffs.add(aDiff); + patch.length2 += aDiff.text.length(); + postpatch_text = postpatch_text.substring(0, char_count2) + + aDiff.text + postpatch_text.substring(char_count2); + break; + case DELETE: + patch.length1 += aDiff.text.length(); + patch.diffs.add(aDiff); + postpatch_text = postpatch_text.substring(0, char_count2) + + postpatch_text.substring(char_count2 + aDiff.text.length()); + break; + case EQUAL: + if (aDiff.text.length() <= 2 * Patch_Margin + && !patch.diffs.isEmpty() && aDiff != diffs.getLast()) { + // Small equality inside a patch. + patch.diffs.add(aDiff); + patch.length1 += aDiff.text.length(); + patch.length2 += aDiff.text.length(); + } + if (aDiff.text.length() >= 2 * Patch_Margin) { + // Time for a new patch. + if (!patch.diffs.isEmpty()) { + patch_addContext(patch, prepatch_text); + patches.add(patch); + patch = new Patch(); + // Unlike Unidiff, our patch lists have a rolling context. + // http://code.google.com/p/google-diff-match-patch/wiki/Unidiff + // Update prepatch text & pos to reflect the application of the + // just completed patch. + prepatch_text = postpatch_text; + char_count1 = char_count2; + } + } + break; + } + // Update the current character count. + if (aDiff.operation != Operation.INSERT) { + char_count1 += aDiff.text.length(); + } + if (aDiff.operation != Operation.DELETE) { + char_count2 += aDiff.text.length(); + } + } + // Pick up the leftover patch if not empty. + if (!patch.diffs.isEmpty()) { + patch_addContext(patch, prepatch_text); + patches.add(patch); + } + return patches; + } + /** + * Given an array of patches, return another array that is identical. + * @param patches Array of patch objects. + * @return Array of patch objects. + */ + public LinkedList patch_deepCopy(LinkedList patches) { + LinkedList patchesCopy = new LinkedList(); + for (Patch aPatch : patches) { + Patch patchCopy = new Patch(); + for (Diff aDiff : aPatch.diffs) { + Diff diffCopy = new Diff(aDiff.operation, aDiff.text); + patchCopy.diffs.add(diffCopy); + } + patchCopy.start1 = aPatch.start1; + patchCopy.start2 = aPatch.start2; + patchCopy.length1 = aPatch.length1; + patchCopy.length2 = aPatch.length2; + patchesCopy.add(patchCopy); + } + return patchesCopy; + } + /** + * Merge a set of patches onto the text. Return a patched text, as well + * as an array of true/false values indicating which patches were applied. + * @param patches Array of patch objects + * @param text Old text. + * @return Two element Object array, containing the new text and an array of + * boolean values. + */ + public Object[] patch_apply(LinkedList patches, String text) { + if (patches.isEmpty()) { + return new Object[]{text, new boolean[0]}; + } + // Deep copy the patches so that no changes are made to originals. + patches = patch_deepCopy(patches); + String nullPadding = patch_addPadding(patches); + text = nullPadding + text + nullPadding; + patch_splitMax(patches); + int x = 0; + // delta keeps track of the offset between the expected and actual location + // of the previous patch. If there are patches expected at positions 10 and + // 20, but the first patch was found at 12, delta is 2 and the second patch + // has an effective expected position of 22. + int delta = 0; + boolean[] results = new boolean[patches.size()]; + for (Patch aPatch : patches) { + int expected_loc = aPatch.start2 + delta; + String text1 = diff_text1(aPatch.diffs); + int start_loc; + int end_loc = -1; + if (text1.length() > this.Match_MaxBits) { + // patch_splitMax will only provide an oversized pattern in the case of + // a monster delete. + start_loc = match_main(text, + text1.substring(0, this.Match_MaxBits), expected_loc); + if (start_loc != -1) { + end_loc = match_main(text, + text1.substring(text1.length() - this.Match_MaxBits), + expected_loc + text1.length() - this.Match_MaxBits); + if (end_loc == -1 || start_loc >= end_loc) { + // Can't find valid trailing context. Drop this patch. + start_loc = -1; + } + } + } else { + start_loc = match_main(text, text1, expected_loc); + } + if (start_loc == -1) { + // No match found. :( + results[x] = false; + // Subtract the delta for this failed patch from subsequent patches. + delta -= aPatch.length2 - aPatch.length1; + } else { + // Found a match. :) + results[x] = true; + delta = start_loc - expected_loc; + String text2; + if (end_loc == -1) { + text2 = text.substring(start_loc, + Math.min(start_loc + text1.length(), text.length())); + } else { + text2 = text.substring(start_loc, + Math.min(end_loc + this.Match_MaxBits, text.length())); + } + if (text1.equals(text2)) { + // Perfect match, just shove the replacement text in. + text = text.substring(0, start_loc) + diff_text2(aPatch.diffs) + + text.substring(start_loc + text1.length()); + } else { + // Imperfect match. Run a diff to get a framework of equivalent + // indices. + LinkedList diffs = diff_main(text1, text2, false); + if (text1.length() > this.Match_MaxBits + && diff_levenshtein(diffs) / (float) text1.length() + > this.Patch_DeleteThreshold) { + // The end points match, but the content is unacceptably bad. + results[x] = false; + } else { + diff_cleanupSemanticLossless(diffs); + int index1 = 0; + for (Diff aDiff : aPatch.diffs) { + if (aDiff.operation != Operation.EQUAL) { + int index2 = diff_xIndex(diffs, index1); + if (aDiff.operation == Operation.INSERT) { + // Insertion + text = text.substring(0, start_loc + index2) + aDiff.text + + text.substring(start_loc + index2); + } else if (aDiff.operation == Operation.DELETE) { + // Deletion + text = text.substring(0, start_loc + index2) + + text.substring(start_loc + diff_xIndex(diffs, + index1 + aDiff.text.length())); + } + } + if (aDiff.operation != Operation.DELETE) { + index1 += aDiff.text.length(); + } + } + } + } + } + x++; + } + // Strip the padding off. + text = text.substring(nullPadding.length(), text.length() + - nullPadding.length()); + return new Object[]{text, results}; + } + /** + * Add some padding on text start and end so that edges can match something. + * Intended to be called only from within patch_apply. + * @param patches Array of patch objects. + * @return The padding string added to each side. + */ + public String patch_addPadding(LinkedList patches) { + int paddingLength = this.Patch_Margin; + String nullPadding = ""; + for (int x = 1; x <= paddingLength; x++) { + nullPadding += String.valueOf((char) x); + } + // Bump all the patches forward. + for (Patch aPatch : patches) { + aPatch.start1 += paddingLength; + aPatch.start2 += paddingLength; + } + // Add some padding on start of first diff. + Patch patch = patches.getFirst(); + LinkedList diffs = patch.diffs; + if (diffs.isEmpty() || diffs.getFirst().operation != Operation.EQUAL) { + // Add nullPadding equality. + diffs.addFirst(new Diff(Operation.EQUAL, nullPadding)); + patch.start1 -= paddingLength; // Should be 0. + patch.start2 -= paddingLength; // Should be 0. + patch.length1 += paddingLength; + patch.length2 += paddingLength; + } else if (paddingLength > diffs.getFirst().text.length()) { + // Grow first equality. + Diff firstDiff = diffs.getFirst(); + int extraLength = paddingLength - firstDiff.text.length(); + firstDiff.text = nullPadding.substring(firstDiff.text.length()) + + firstDiff.text; + patch.start1 -= extraLength; + patch.start2 -= extraLength; + patch.length1 += extraLength; + patch.length2 += extraLength; + } + // Add some padding on end of last diff. + patch = patches.getLast(); + diffs = patch.diffs; + if (diffs.isEmpty() || diffs.getLast().operation != Operation.EQUAL) { + // Add nullPadding equality. + diffs.addLast(new Diff(Operation.EQUAL, nullPadding)); + patch.length1 += paddingLength; + patch.length2 += paddingLength; + } else if (paddingLength > diffs.getLast().text.length()) { + // Grow last equality. + Diff lastDiff = diffs.getLast(); + int extraLength = paddingLength - lastDiff.text.length(); + lastDiff.text += nullPadding.substring(0, extraLength); + patch.length1 += extraLength; + patch.length2 += extraLength; + } + return nullPadding; + } + /** + * Look through the patches and break up any which are longer than the + * maximum limit of the match algorithm. + * @param patches LinkedList of Patch objects. + */ + public void patch_splitMax(LinkedList patches) { + int patch_size; + String precontext, postcontext; + Patch patch; + int start1, start2; + boolean empty; + Operation diff_type; + String diff_text; + ListIterator pointer = patches.listIterator(); + Patch bigpatch = pointer.hasNext() ? pointer.next() : null; + while (bigpatch != null) { + if (bigpatch.length1 <= Match_MaxBits) { + bigpatch = pointer.hasNext() ? pointer.next() : null; + continue; + } + // Remove the big old patch. + pointer.remove(); + patch_size = Match_MaxBits; + start1 = bigpatch.start1; + start2 = bigpatch.start2; + precontext = ""; + while (!bigpatch.diffs.isEmpty()) { + // Create one of several smaller patches. + patch = new Patch(); + empty = true; + patch.start1 = start1 - precontext.length(); + patch.start2 = start2 - precontext.length(); + if (precontext.length() != 0) { + patch.length1 = patch.length2 = precontext.length(); + patch.diffs.add(new Diff(Operation.EQUAL, precontext)); + } + while (!bigpatch.diffs.isEmpty() + && patch.length1 < patch_size - Patch_Margin) { + diff_type = bigpatch.diffs.getFirst().operation; + diff_text = bigpatch.diffs.getFirst().text; + if (diff_type == Operation.INSERT) { + // Insertions are harmless. + patch.length2 += diff_text.length(); + start2 += diff_text.length(); + patch.diffs.addLast(bigpatch.diffs.removeFirst()); + empty = false; + } else if (diff_type == Operation.DELETE && patch.diffs.size() == 1 + && patch.diffs.getFirst().operation == Operation.EQUAL + && diff_text.length() > 2 * patch_size) { + // This is a large deletion. Let it pass in one chunk. + patch.length1 += diff_text.length(); + start1 += diff_text.length(); + empty = false; + patch.diffs.add(new Diff(diff_type, diff_text)); + bigpatch.diffs.removeFirst(); + } else { + // Deletion or equality. Only take as much as we can stomach. + diff_text = diff_text.substring(0, Math.min(diff_text.length(), + patch_size - patch.length1 - Patch_Margin)); + patch.length1 += diff_text.length(); + start1 += diff_text.length(); + if (diff_type == Operation.EQUAL) { + patch.length2 += diff_text.length(); + start2 += diff_text.length(); + } else { + empty = false; + } + patch.diffs.add(new Diff(diff_type, diff_text)); + if (diff_text.equals(bigpatch.diffs.getFirst().text)) { + bigpatch.diffs.removeFirst(); + } else { + bigpatch.diffs.getFirst().text = bigpatch.diffs.getFirst().text + .substring(diff_text.length()); + } + } + } + // Compute the head context for the next patch. + precontext = diff_text2(patch.diffs); + precontext = precontext.substring(Math.max(0, precontext.length() + - Patch_Margin)); + // Append the end context for this patch. + if (diff_text1(bigpatch.diffs).length() > Patch_Margin) { + postcontext = diff_text1(bigpatch.diffs).substring(0, Patch_Margin); + } else { + postcontext = diff_text1(bigpatch.diffs); + } + if (postcontext.length() != 0) { + patch.length1 += postcontext.length(); + patch.length2 += postcontext.length(); + if (!patch.diffs.isEmpty() + && patch.diffs.getLast().operation == Operation.EQUAL) { + patch.diffs.getLast().text += postcontext; + } else { + patch.diffs.add(new Diff(Operation.EQUAL, postcontext)); + } + } + if (!empty) { + pointer.add(patch); + } + } + bigpatch = pointer.hasNext() ? pointer.next() : null; + } + } + /** + * Take a list of patches and return a textual representation. + * @param patches List of Patch objects. + * @return Text representation of patches. + */ + public String patch_toText(List patches) { + StringBuilder text = new StringBuilder(); + for (Patch aPatch : patches) { + text.append(aPatch); + } + return text.toString(); + } + /** + * Parse a textual representation of patches and return a List of Patch + * objects. + * @param textline Text representation of patches. + * @return List of Patch objects. + * @throws IllegalArgumentException If invalid input. + */ + public List patch_fromText(String textline) + throws IllegalArgumentException { + List patches = new LinkedList(); + if (textline.length() == 0) { + return patches; + } + List textList = Arrays.asList(textline.split("\n")); + LinkedList text = new LinkedList(textList); + Patch patch; + Pattern patchHeader + = Pattern.compile("^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$"); + Matcher m; + char sign; + String line; + while (!text.isEmpty()) { + m = patchHeader.matcher(text.getFirst()); + if (!m.matches()) { + throw new IllegalArgumentException( + "Invalid patch string: " + text.getFirst()); + } + patch = new Patch(); + patches.add(patch); + patch.start1 = Integer.parseInt(m.group(1)); + if (m.group(2).length() == 0) { + patch.start1--; + patch.length1 = 1; + } else if ("0".equals(m.group(2))) { + patch.length1 = 0; + } else { + patch.start1--; + patch.length1 = Integer.parseInt(m.group(2)); + } + patch.start2 = Integer.parseInt(m.group(3)); + if (m.group(4).length() == 0) { + patch.start2--; + patch.length2 = 1; + } else if ("0".equals(m.group(4))) { + patch.length2 = 0; + } else { + patch.start2--; + patch.length2 = Integer.parseInt(m.group(4)); + } + text.removeFirst(); + + while (!text.isEmpty()) { + try { + sign = text.getFirst().charAt(0); + } catch (IndexOutOfBoundsException e) { + // Blank line? Whatever. + text.removeFirst(); + continue; + } + line = text.getFirst().substring(1); + line = line.replace("+", "%2B"); // decode would change all "+" to " " + try { + line = URLDecoder.decode(line, "UTF-8"); + } catch (UnsupportedEncodingException e) { + // Not likely on modern system. + throw new Error("This system does not support UTF-8.", e); + } catch (IllegalArgumentException e) { + // Malformed URI sequence. + throw new IllegalArgumentException( + "Illegal escape in patch_fromText: " + line, e); + } + if (sign == '-') { + // Deletion. + patch.diffs.add(new Diff(Operation.DELETE, line)); + } else if (sign == '+') { + // Insertion. + patch.diffs.add(new Diff(Operation.INSERT, line)); + } else if (sign == ' ') { + // Minor equality. + patch.diffs.add(new Diff(Operation.EQUAL, line)); + } else if (sign == '@') { + // Start of next patch. + break; + } else { + // WTF? + throw new IllegalArgumentException( + "Invalid patch mode '" + sign + "' in: " + line); + } + text.removeFirst(); + } + } + return patches; + } + + + /** + * Class representing one diff operation. + */ + public static class Diff { + /** + * One of: INSERT, DELETE or EQUAL. + */ + public Operation operation; + /** + * The text associated with this diff operation. + */ + public String text; + + /** + * Constructor. Initializes the diff with the provided values. + * @param operation One of INSERT, DELETE or EQUAL. + * @param text The text being applied. + */ + public Diff(Operation operation, String text) { + // Construct a diff with the specified operation and text. + this.operation = operation; + this.text = text; + } + + + /** + * Display a human-readable version of this Diff. + * @return text version. + */ + @Override + public String toString() { + String prettyText = this.text.replace('\n', '\u00b6'); + return "Diff(" + this.operation + ",\"" + prettyText + "\")"; + } + + + /** + * Is this Diff equivalent to another Diff? + * @param d Another Diff to compare against. + * @return true or false. + */ + @Override + public boolean equals(Object d) { + try { + return (((Diff) d).operation == this.operation) + && (((Diff) d).text.equals(this.text)); + } catch (ClassCastException e) { + return false; + } + } + } + + + /** + * Class representing one patch operation. + */ + public static class Patch { + public LinkedList diffs; + public int start1; + public int start2; + public int length1; + public int length2; + + + /** + * Constructor. Initializes with an empty list of diffs. + */ + public Patch() { + this.diffs = new LinkedList(); + } + + + /** + * Emmulate GNU diff's format. + * Header: @@ -382,8 +481,9 @@ + * Indicies are printed as 1-based, not 0-based. + * @return The GNU diff string. + */ + @Override + public String toString() { + String coords1, coords2; + if (this.length1 == 0) { + coords1 = this.start1 + ",0"; + } else if (this.length1 == 1) { + coords1 = Integer.toString(this.start1 + 1); + } else { + coords1 = (this.start1 + 1) + "," + this.length1; + } + if (this.length2 == 0) { + coords2 = this.start2 + ",0"; + } else if (this.length2 == 1) { + coords2 = Integer.toString(this.start2 + 1); + } else { + coords2 = (this.start2 + 1) + "," + this.length2; + } + StringBuilder text = new StringBuilder(); + text.append("@@ -").append(coords1).append(" +").append(coords2) + .append(" @@\n"); + // Escape the body of the patch with %xx notation. + for (Diff aDiff : this.diffs) { + switch (aDiff.operation) { + case INSERT: + text.append('+'); + break; + case DELETE: + text.append('-'); + break; + case EQUAL: + text.append(' '); + break; + } + try { + text.append(URLEncoder.encode(aDiff.text, "UTF-8").replace('+', ' ')) + .append("\n"); + } catch (UnsupportedEncodingException e) { + // Not likely on modern system. + throw new Error("This system does not support UTF-8.", e); + } + } + return unescapeForEncodeUriCompatability(text.toString()); + } + } + + + /** + * Unescape selected chars for compatability with JavaScript's encodeURI. + * In speed critical applications this could be dropped since the + * receiving application will certainly decode these fine. + * Note that this function is case-sensitive. Thus "%3f" would not be + * unescaped. But this is ok because it is only called with the output of + * URLEncoder.encode which returns uppercase hex. + * + * Example: "%3F" -> "?", "%24" -> "$", etc. + * + * @param str The string to escape. + * @return The escaped string. + */ + private static String unescapeForEncodeUriCompatability(String str) { + return str.replace("%21", "!").replace("%7E", "~") + .replace("%27", "'").replace("%28", "(").replace("%29", ")") + .replace("%3B", ";").replace("%2F", "/").replace("%3F", "?") + .replace("%3A", ":").replace("%40", "@").replace("%26", "&") + .replace("%3D", "=").replace("%2B", "+").replace("%24", "$") + .replace("%2C", ",").replace("%23", "#"); + } + + public String getHtmlDiffString(String text1,String text2){ + return diff_prettyHtml(diff_main(text1,text2)); + } + + public static void main(String[] args){ + DiffMatchPatch dmp = new DiffMatchPatch(); + String text1 = "我方在“福市财政资金补助项目管理系统”的项目实施过程,为保证该项目的工程进度、质量,符合数办项目的实施管理规范与要求。"; + String text2 = "我方在“福州市财政资金补助项目管理系统”的项目实施过程,为保证该haha项目的工程进度、质量,符合目的实施管理规范与要求。"; + System.out.println(dmp.getHtmlDiffString(text1,text2)); + } +} diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/EventUtils/EventEditHistoryHighLightUtil.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/EventUtils/EventEditHistoryHighLightUtil.java new file mode 100644 index 00000000..e8058b57 --- /dev/null +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/EventUtils/EventEditHistoryHighLightUtil.java @@ -0,0 +1,209 @@ +package com.adc.da.slrs.standardSplit.EventUtils; + +/** + * @Description: TODO + * @author: super_liu + * @date: 2021年11月28日 12:28 + */ + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * 文本差异高亮算法 + * + * @Author : cron + * @Date: 2020-01-15 + */ +@SuppressWarnings("all") +public class EventEditHistoryHighLightUtil { + + /** + * 传入2个字符串进行相比高亮显示 + * eg: + * 原数据一:王五张三 + * 原数据二:张三李四 + * 王五张三 + * 张三李四 + */ + + public static String[] getHighLightDifferentOld(String a, String b) { + String[] temp = getDiff(a, b); + String[] result = {getHighLight(a, temp[0]), getHighLight(b, temp[1])}; + return result; + } + + private static String getHighLight(String source, String temp) { + StringBuffer sb = new StringBuffer(); + char[] sourceChars = source.toCharArray(); + char[] tempChars = temp.toCharArray(); + boolean flag = false; + for (int i = 0; i < sourceChars.length; i++) { + if (tempChars[i] != ' ') { + if (i == 0) { + sb.append("").append(sourceChars[i]); + } else if (flag) { + sb.append(sourceChars[i]); + } else { + sb.append("").append(sourceChars[i]); + } + flag = true; + if (i == sourceChars.length - 1) { + sb.append(""); + } + } else if (flag) { + sb.append("").append(sourceChars[i]); + flag = false; + } else { + sb.append(sourceChars[i]); + } + } + return sb.toString(); + } + + public static String[] getDiff(String a, String b) { + String[] result = null; + //选取长度较小的字符串用来穷举子串 + if (a.length() < b.length()) { + result = getDiff(a, b, 0, a.length()); + } else { + result = getDiff(b, a, 0, b.length()); + result = new String[]{result[1], result[0]}; + } + return result; + } + + /** + * 将a的指定部分与b进行比较生成比对结果 + */ + private static String[] getDiff(String a, String b, int start, int end) { + String[] result = new String[]{a, b}; + int len = result[0].length(); + while (len > 0) { + for (int i = start; i < end - len + 1; i++) { + String sub = result[0].substring(i, i + len); + int idx = -1; + if ((idx = result[1].indexOf(sub)) != -1) { + result[0] = setEmpty(result[0], i, i + len); + result[1] = setEmpty(result[1], idx, idx + len); + if (i > 0) { + //递归获取空白区域左边差异 + result = getDiff(result[0], result[1], 0, i); + } + if (i + len < end) { + //递归获取空白区域右边差异 + result = getDiff(result[0], result[1], i + len, end); + } + len = 0;//退出while循环 + break; + } + } + len = len / 2; + } + return result; + } + + /** + * 将字符串s指定的区域设置成空格 + */ + public static String setEmpty(String s, int start, int end) { + char[] array = s.toCharArray(); + for (int i = start; i < end; i++) { + array[i] = ' '; + } + return new String(array); + } + + //--------------new ------------------------- + + public static String[] getHighLightDifferent(String altbe, String altaf) { + //字符串1 altbe 字符串2 altaf + List beList = rememberSpacing(altbe); + List afList = rememberSpacing(altaf); + altbe = altbe.replace(" ", ""); + altaf = altaf.replace(" ", ""); + LinkedList t = new DiffMatchPatch().diff_main(altbe, altaf); + StringBuffer s1 = new StringBuffer(); + StringBuffer s2 = new StringBuffer(); + Integer indexBe = 0; + Integer indexAf = 0; + for (DiffMatchPatch.Diff diff : t) { + StringBuffer diffTextBe = new StringBuffer(diff.text); + StringBuffer diffTextAf = new StringBuffer(diff.text); + if ("EQUAL".equalsIgnoreCase(diff.operation.toString())) { + addSpacing(beList, indexBe, diffTextBe); + addSpacing(afList, indexAf, diffTextAf); + s1.append(diffTextBe); + s2.append(diffTextAf); + indexBe += diffTextBe.length(); + indexAf += diffTextAf.length(); + } + indexBe = appendString2("DELETE", diff, s1, s2, beList, indexBe); + indexAf = appendString2("INSERT", diff, s2, s1, afList, indexAf); + } + String[] result = new String[2]; + result[0] = s1.toString(); + result[1] = s2.toString(); + return result; + } + +// public static void appendString(String type, Diff diff, StringBuffer sbOne, StringBuffer sbTwo) { +// if (type.equals(diff.operation.toString())) { +// if (" ".equals(diff.text)) { +// sbOne.append(" "); +// sbTwo.append(" "); +// } else { +// sbOne.append("").append(diff.text).append(""); +// } +// } +// } + + private static List rememberSpacing(String str) { + List list = new ArrayList<>(); + for (int i = 0; i < str.length(); i++) { + if (' ' == str.charAt(i)) { + list.add(i); + } + } + return list; + } + + public static void addSpacing(List list, Integer index, StringBuffer str) { + for (Integer o : list) { + if (o >= index && o < index + str.length()) { + str.insert(o - index, ' '); + } + } + } + + public static Integer appendString2(String type, DiffMatchPatch.Diff diff, StringBuffer sbOne, + StringBuffer sbTwo, List list, Integer i) { + Integer result = i; + if (type.equals(diff.operation.toString())) { + StringBuffer sb = new StringBuffer(diff.text); + for (Integer o : list) { + if (o >= i && o < i + sb.length()) { + sb.insert(o - i, ' '); + } + } + sbOne.append("").append(sb).append(""); + result = i + sb.length(); + } + return result; + } + + public static void main(String[] args) { + String a = "测试测试测试仅关注界面和功能,数据准确性在暂不测试"; + String b = "提交留言数据仅关注界面和功能,数据准确性在暂不测试"; + String[] anb = getHighLightDifferent(a, b); + System.out.println(Arrays.toString(anb)); + +// String altbe = "提交留言数据仅关注界面和 功能,数据准确性在暂不测试"; +// String altaf = "提交留言数据仅关注界面和功能,数据准确性在暂不测试提交 留言数据仅关注界面和功能,数据准确性在暂不测试"; +// String[] highLightDifferentNew = getHighLightDifferent(altbe, altaf); +// System.out.println(Arrays.toString(highLightDifferentNew)); + } + +} diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/controller/SarStandCompareHisEOController.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/controller/SarStandCompareHisEOController.java index 4441fd9e..ef94128e 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/controller/SarStandCompareHisEOController.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/controller/SarStandCompareHisEOController.java @@ -5,8 +5,10 @@ import com.adc.da.http.PageInfo; import com.adc.da.person.dao.PersonCollectEODao; import com.adc.da.person.dao.PersonShareEODao; import com.adc.da.slrs.standardSplit.dao.SarStandCompareHisEODao; +import com.adc.da.slrs.standardSplit.entity.SarFileSplitInfoEO; import com.adc.da.slrs.standardSplit.entity.SarStandCompareHisEO; import com.adc.da.slrs.standardSplit.entity.SarStandCompareHisEOPage; +import com.adc.da.slrs.standardSplit.service.SarFileSplitInfoEOService; import com.adc.da.slrs.standardSplit.service.SarItemsCompareHisEOService; import com.adc.da.slrs.standardSplit.service.SarStandCompareHisEOService; import com.adc.da.slrs.standardSplit.service.SarStandItemsCompareHisEOService; @@ -36,6 +38,9 @@ public class SarStandCompareHisEOController extends BaseController> clauseComparison(String oldItemId, String newItemId, String standHisId) throws Exception { - Map resultMap = sarStandCompareHisEOService.clauseComparison(oldItemId,newItemId,standHisId); + public ResponseMessage> clauseComparison(String oldItemId, String newItemId, String standHisId,String flag) throws Exception { + Map resultMap = sarStandCompareHisEOService.clauseComparisonEvent(oldItemId,newItemId,standHisId,flag); return Result.success(resultMap); } @ApiOperation(value = "全文比对") @PostMapping("/fullTextComparison") public ResponseMessage fullTextComparison(String leftStandard, String rightStandard) throws Exception { - String id=UUIDUtils.randomUUID(32); - SarStandCompareHisEO sarStandCompareHisEO =new SarStandCompareHisEO(); + SarFileSplitInfoEO leftInfo = sarFileSplitInfoEOService.selectByPrimaryKey(leftStandard); + SarFileSplitInfoEO rightInfo = sarFileSplitInfoEOService.selectByPrimaryKey(rightStandard); + //保存标准比对历史表数据 + SarStandCompareHisEO sarStandCompareHisEO = new SarStandCompareHisEO(); +// String id = UUIDUtils.randomUUID20(); + String id=UUIDUtils.randomUUID(32); sarStandCompareHisEO.setId(id); + sarStandCompareHisEO.setOldStandId(leftStandard); + sarStandCompareHisEO.setNewStandId(rightStandard); + sarStandCompareHisEO.setOldFileType(leftInfo.getFileType()); + sarStandCompareHisEO.setNewFileType(rightInfo.getFileType()); + sarStandCompareHisEO.setOldStandName(leftInfo.getStandNameSplit()); + sarStandCompareHisEO.setNewStandName(rightInfo.getStandNameSplit()); + sarStandCompareHisEO.setOldStandNum(leftInfo.getStandNumSplit()); + sarStandCompareHisEO.setNewStandNum(rightInfo.getStandNumSplit()); + sarStandCompareHisEO.setOldSarType(leftInfo.getSarType()); + sarStandCompareHisEO.setNewSarType(rightInfo.getSarType()); + sarStandCompareHisEO.setCreateTime(new Date()); + sarStandCompareHisEO.setModifyTime(new Date()); + sarStandCompareHisEO.setCreateUser(LoginUserUtil.getUserId()); + sarStandCompareHisEO.setModifyUser(LoginUserUtil.getUserId()); sarStandCompareHisEO.setCompareStatus("比对中"); sarStandCompareHisEO.setCompareType("全文比对"); sarStandCompareHisEO.setCreateTime(new Date()); diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/service/SarStandCompareHisEOService.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/service/SarStandCompareHisEOService.java index d0dfd8a9..1b4c8683 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/service/SarStandCompareHisEOService.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/service/SarStandCompareHisEOService.java @@ -21,5 +21,7 @@ public interface SarStandCompareHisEOService { Map clauseComparison(String oldItemId, String newItemId, String standHisId); + Map clauseComparisonEvent(String oldItemId, String newItemId, String standHisId,String flag); + Map fullTextComparison(String leftStandard, String rightStandard,String id) throws Exception; } diff --git a/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/service/impl/SarStandCompareHisEOServiceImpl.java b/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/service/impl/SarStandCompareHisEOServiceImpl.java index cf68b7c2..937dd5e1 100644 --- a/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/service/impl/SarStandCompareHisEOServiceImpl.java +++ b/adc-da-slrs/src/main/java/com/adc/da/slrs/standardSplit/service/impl/SarStandCompareHisEOServiceImpl.java @@ -1,6 +1,7 @@ package com.adc.da.slrs.standardSplit.service.impl; import com.adc.da.person.service.IPersonCollectEOService; +import com.adc.da.slrs.standardSplit.EventUtils.EventEditHistoryHighLightUtil; import com.adc.da.slrs.standardSplit.dao.SarStandAttrDetailsEODao; import com.adc.da.slrs.standardSplit.dao.SarStandCompareHisEODao; import com.adc.da.slrs.standardSplit.entity.*; @@ -14,6 +15,7 @@ import com.adc.da.utils.treetool.TreeNode; import com.adc.da.utils.util.CompHanLPUtils; import com.adc.da.utils.util.DiffUtils; import org.apache.commons.lang.StringUtils; +import org.apache.poi.util.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -112,6 +114,138 @@ public class SarStandCompareHisEOServiceImpl implements SarStandCompareHisEOServ return sarStandCompareHisEODao.deleteByPrimaryKey(id); } + @Override + public Map clauseComparisonEvent(String oldItemId, String newItemId, String standHisId, String flag) { + Map resultMap = new HashMap(); + String oldTxt = ""; + SarFileSplitItemsValEOPage oldPage = new SarFileSplitItemsValEOPage(); + oldPage.setItemId(oldItemId); + oldPage.setType("TEXT"); + oldPage.setOrderBy("DISPLAY_SEQ,ID"); + List oldList = sarFileSplitItemsValEOService.queryByList(oldPage); + if(oldList!=null && !oldList.isEmpty()){ + for(int i = 1;i<=oldList.size();i++){ + if(i==oldList.size()) { + oldTxt += oldList.get(i-1).getItemContent(); + }else{ + oldTxt += oldList.get(i-1).getItemContent() + "i#2\n"; + } + } + } + String newTxt = ""; + SarFileSplitItemsValEOPage newPage = new SarFileSplitItemsValEOPage(); + newPage.setItemId(newItemId); + newPage.setType("TEXT"); + newPage.setOrderBy("DISPLAY_SEQ,ID"); + List newList = sarFileSplitItemsValEOService.queryByList(newPage); + if(newList!=null && !newList.isEmpty()){ + for(int i = 1;i<=newList.size();i++){ + if(i==newList.size()) { + newTxt += newList.get(i-1).getItemContent(); + }else{ + newTxt += newList.get(i-1).getItemContent() + "i#2\n"; + } + } + } + String similarityDegree=""; + double similarity = 100.00; + if(!StringUtils.isNotBlank(oldTxt.trim()) && !StringUtils.isNotBlank(newTxt.trim())){ + similarityDegree = "100.00"; + }else if(StringUtils.isNotBlank(oldTxt.trim()) && StringUtils.isNotBlank(newTxt.trim())){ + similarity = CompHanLPUtils.findSimilarity(oldTxt.trim(), newTxt.trim()); + NumberFormat nf = java.text.NumberFormat.getPercentInstance(); + //nf.setMaximumIntegerDigits(2);//小数点前保留几位 + nf.setMinimumFractionDigits(2);// 小数点后保留几位 + similarityDegree = nf.format(similarity); + }else{ + similarity = 0.00; + similarityDegree = "0.00"; + } + resultMap.put("similarityDegree",similarityDegree); + List leftString = new ArrayList<>(); + List rightString = new ArrayList<>(); + if(similarity >= 0.6){ +// DiffUtils diffUtils = new DiffUtils(); +// List htmlDiffStr = diffUtils.getHtmlDiffStr(oldTxt.trim(), newTxt.trim()); +// List stringList1 = Arrays.asList(htmlDiffStr.get(0).split("
    ")); +// for(String left : stringList1){ +// StringBuilder stringBuilder = new StringBuilder(left); +// stringBuilder.append("
    "); +// leftString.add(stringBuilder.toString()); +// } +// List stringList2 = Arrays.asList(htmlDiffStr.get(1).split("
    ")); +// for(String right : stringList2){ +// StringBuilder stringBuilder = new StringBuilder(right); +// stringBuilder.append("
    "); +// rightString.add(stringBuilder.toString()); +// } + String[] anb = EventEditHistoryHighLightUtil.getHighLightDifferent(oldTxt.trim(), newTxt.trim()); + if(StringUtils.isNotBlank(flag) && flag.equals("2")){ + anb[0] = anb[0].replaceAll("red;", "#000000;background-color: red;").replaceAll("i#2\n", "
    "); + anb[1] = anb[1].replaceAll("red;", "#000000;background-color: rgb(51, 145, 206);").replaceAll("i#2\n", "
    "); + }else { + anb[0] = anb[0].replaceAll("red;", "#000000;background-color: rgb(51, 145, 206);").replaceAll("i#2\n", "
    "); + anb[1] = anb[1].replaceAll("red;", "#000000;background-color: red;").replaceAll("i#2\n", "
    "); + } + resultMap.put("leftString",anb[0]); + resultMap.put("rightString",anb[1]); + }else{ + String oldTxtTemp = oldTxt.replace("i#2\n", "
    "); + List stringList1 = Arrays.asList(oldTxtTemp.split("
    ")); + for(String left : stringList1){ + StringBuilder stringBuilder = new StringBuilder(left); + stringBuilder.append(""); + stringBuilder.insert(0,"
    "); + leftString.add(stringBuilder.toString()); + } + resultMap.put("leftString",leftString); + String newTxtTemp = newTxt.replace("i#2\n", "
    "); + List stringList2 = Arrays.asList(newTxtTemp.split("
    ")); + for(String right : stringList2){ + StringBuilder stringBuilder = new StringBuilder(right); + stringBuilder.append("
    "); + stringBuilder.insert(0,"
    "); + rightString.add(stringBuilder.toString()); + } + resultMap.put("rightString",rightString); + } + //往条款比对历史表中添加数据 + if(standHisId != null && !standHisId.isEmpty()){ + SarFileSplitItemsEO leftEo = sarFileSplitItemsEOService.selectByPrimaryKey(oldItemId); + SarFileSplitItemsEO rightEo = sarFileSplitItemsEOService.selectByPrimaryKey(newItemId); + String leftItemsText = ""; + if(leftString != null && !leftString.isEmpty()){ + for(String left : leftString){ + leftItemsText += left; + } + } + String rightItemsText = ""; + if(rightString != null && !rightString.isEmpty()){ + for(String right : rightString){ + rightItemsText += right; + } + } + SarItemsCompareHisEO sarItemsCompareHisEO = new SarItemsCompareHisEO(); + sarItemsCompareHisEO.setId(UUIDUtils.randomUUID20()); + sarItemsCompareHisEO.setOldItemsId(leftEo.getId()); + sarItemsCompareHisEO.setOldItemsName(leftEo.getItemsName()); + sarItemsCompareHisEO.setOldItemsNum(leftEo.getItemsNum()); + sarItemsCompareHisEO.setOldItemsText(leftItemsText); + sarItemsCompareHisEO.setNewItemsId(rightEo.getId()); + sarItemsCompareHisEO.setNewItemsName(rightEo.getItemsName()); + sarItemsCompareHisEO.setNewItemsNum(rightEo.getItemsNum()); + sarItemsCompareHisEO.setNewItemsText(rightItemsText); + sarItemsCompareHisEO.setStandHisId(standHisId); + sarItemsCompareHisEO.setSimilarityDegree(similarityDegree); + sarItemsCompareHisEO.setCreateUser(LoginUserUtil.getUserId()); + sarItemsCompareHisEO.setModifyUser(LoginUserUtil.getUserId()); + sarItemsCompareHisEO.setModifyTime(new Date()); + sarItemsCompareHisEO.setCreateTime(new Date()); + sarItemsCompareHisEOService.insertSelective(sarItemsCompareHisEO); + } + return resultMap; + } + @Override public Map clauseComparison(String oldItemId, String newItemId, String standHisId) { Map resultMap = new HashMap(); @@ -326,20 +460,6 @@ public class SarStandCompareHisEOServiceImpl implements SarStandCompareHisEOServ SarStandCompareHisEO sarStandCompareHisEO = new SarStandCompareHisEO(); // String id = UUIDUtils.randomUUID20(); sarStandCompareHisEO.setId(id); - sarStandCompareHisEO.setOldStandId(leftStandId); - sarStandCompareHisEO.setNewStandId(rightStandId); - sarStandCompareHisEO.setOldFileType(leftInfo.getFileType()); - sarStandCompareHisEO.setNewFileType(rightInfo.getFileType()); - sarStandCompareHisEO.setOldStandName(leftInfo.getStandNameSplit()); - sarStandCompareHisEO.setNewStandName(rightInfo.getStandNameSplit()); - sarStandCompareHisEO.setOldStandNum(leftInfo.getStandNumSplit()); - sarStandCompareHisEO.setNewStandNum(rightInfo.getStandNumSplit()); - sarStandCompareHisEO.setOldSarType(leftInfo.getSarType()); - sarStandCompareHisEO.setNewSarType(rightInfo.getSarType()); - sarStandCompareHisEO.setCreateTime(new Date()); - sarStandCompareHisEO.setModifyTime(new Date()); - sarStandCompareHisEO.setCreateUser(LoginUserUtil.getUserId()); - sarStandCompareHisEO.setModifyUser(LoginUserUtil.getUserId()); sarStandCompareHisEO.setCompareType(compareType); sarStandCompareHisEO.setCompareStatus("比对完成"); dao.updateByPrimaryKeySelective(sarStandCompareHisEO); diff --git a/adc-da-slrs/src/main/resources/mybatis/mapper/sarLawsAttrDetailedList/SarLawsAttrDetailedListMapper.xml b/adc-da-slrs/src/main/resources/mybatis/mapper/sarLawsAttrDetailedList/SarLawsAttrDetailedListMapper.xml index 0984ff19..17fe6030 100644 --- a/adc-da-slrs/src/main/resources/mybatis/mapper/sarLawsAttrDetailedList/SarLawsAttrDetailedListMapper.xml +++ b/adc-da-slrs/src/main/resources/mybatis/mapper/sarLawsAttrDetailedList/SarLawsAttrDetailedListMapper.xml @@ -99,95 +99,43 @@ order by number - - + + + SELECT + , + attr.CLLX AS APPLY_TYPE , + attr.ZRGCS AS DUTY_ENGINEER , + NULL AS ITEMS_ID , + NULL AS ITEMS_NUM , + NULL AS ITEMS_NAME , + NULL AS POLICY_ID , + NULL AS POLICY_NAME , + MARK , + POWER, + attr.XCXSSRQ AS XCXSSRQ , + attr.ZCCSSRQ AS ZCCSSRQ + FROM sar_stand_warning AS warning + LEFT JOIN sar_standards_info AS sarInfo on sarInfo.id=warning.STAND_ID + LEFT JOIN sar_stand_attr_info AS attr on attr.STAND_ID=warning.STAND_ID + + POWER = '1' + + + + AND attr.CLLX LIKE CONCAT('%', #{waringEO.applyType},'%') + + + AND ( + DATE_FORMAT( attr.XCXSSRQ, '%Y-%m-%d') >= DATE_FORMAT( + #{waringEO.startXCXSSRQ}, + '%Y-%m-%d' + ) + + AND + DATE_FORMAT( attr.XCXSSRQ, '%Y-%m-%d') <= DATE_FORMAT( + #{waringEO.endXCXSSRQ}, + '%Y-%m-%d' + ) + ) + + + AND ( + DATE_FORMAT( attr.ZCCSSRQ, '%Y-%m-%d') >= DATE_FORMAT( + #{waringEO.startZCCSSRQ}, + '%Y-%m-%d' + ) + + AND + DATE_FORMAT( attr.ZCCSSRQ, '%Y-%m-%d') <= DATE_FORMAT( + #{waringEO.endZCCSSRQ}, + '%Y-%m-%d' + ) + ) + + + + + UNION ALL + + SELECT + , + items.APPLY_ARCTIC AS APPLY_TYPE , + items.DUTY_ENGINEER AS DUTY_ENGINEER , + items.ID AS ITEMS_ID , + items.ITEMS_NUM , + items.ITEMS_NAME , + NULL AS POLICY_ID , + NULL AS POLICY_NAME , + MARK , + POWER, + items.XCXSSRQ AS XCXSSRQ , + items.ZCCSSRQ AS ZCCSSRQ + FROM + sar_stand_warning AS warning + LEFT JOIN sar_standards_info AS sarInfo ON sarInfo.id = warning.STAND_ID + LEFT JOIN sar_stand_items AS items ON items.STAND_ID = warning.STAND_ID + LEFT JOIN sar_stand_attr_info AS attr ON attr.STAND_ID = warning.STAND_ID + + POWER = '1' + + + + AND items.APPLY_ARCTIC LIKE CONCAT('%', #{waringEO.applyType},'%') + + + + AND ( + DATE_FORMAT( items.XCXSSRQ, '%Y-%m-%d') >= DATE_FORMAT(#{waringEO.startXCXSSRQ},'%Y-%m-%d') + AND + DATE_FORMAT( items.XCXSSRQ, '%Y-%m-%d') <= DATE_FORMAT(#{waringEO.endXCXSSRQ},'%Y-%m-%d') + ) + + + + AND( + DATE_FORMAT( items.ZCCSSRQ, '%Y-%m-%d') >= DATE_FORMAT(#{waringEO.startZCCSSRQ},'%Y-%m-%d') + AND + DATE_FORMAT( items.ZCCSSRQ, '%Y-%m-%d') <= DATE_FORMAT(#{waringEO.endZCCSSRQ},'%Y-%m-%d' ) + ) + + + + + + + + diff --git a/adc-da-sys/src/main/java/com/adc/da/att/controller/AttFileEOController.java b/adc-da-sys/src/main/java/com/adc/da/att/controller/AttFileEOController.java index 636c2f41..475d5f7d 100644 --- a/adc-da-sys/src/main/java/com/adc/da/att/controller/AttFileEOController.java +++ b/adc-da-sys/src/main/java/com/adc/da/att/controller/AttFileEOController.java @@ -21,6 +21,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Async; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import sun.misc.BASE64Encoder; @@ -30,6 +31,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.constraints.NotNull; import java.io.*; +import java.net.URL; +import java.net.URLConnection; import java.net.URLEncoder; import java.nio.file.Files; import java.text.SimpleDateFormat; @@ -56,6 +59,9 @@ public class AttFileEOController { @Value("${file.path}") private String filePath;//文件存储路径 + @Value("${stand.edit.file.path}") + private String standEditFilePath; + // @Autowired // private RoleEOService roleEOService; // @@ -66,6 +72,89 @@ public class AttFileEOController { private String uploadFileWhiteLists; //上传文件白名单 + @ApiOperation(value = "|获取企标文件") + @GetMapping("/getBusStandFileByAttId") + public ResponseMessage getBusStandFileByAttId(String attId){ + AttFileEO attFileEO = attFileEOService.saveOrGetBusFileInfo(attId); + return Result.success(attFileEO); + } + + @ApiOperation(value = "|onlyOffice接收文件") + @PostMapping("/recieveFile") + public void recieveFile(HttpServletRequest request, HttpServletResponse response, String fileNm,String standNo){ + logger.info("**********进入onlyoffice接收文档接口************"); + try { + PrintWriter writer = response.getWriter(); + String body = ""; + try { + Scanner scanner = new Scanner(request.getInputStream()); + scanner.useDelimiter("\\A"); + body = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + } catch (Exception ex) { + writer.write("get request.getInputStream error:" + ex.getMessage()); + return; + } + + if (body.isEmpty()) { + writer.write("empty request.getInputStream"); + return; + } + + net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(body); + logger.info("**********onlyoffice接收文档接口获得结果body************" + body); + int status = (Integer) jsonObj.get("status"); + + int saved = 0; + if (status == 2 || status == 3)//MustSave, Corrupted + { + String downloadUri = (String) jsonObj.get("url"); + + try { + logger.info("**********onlyoffice接收文档接口获得downloadUri************" + downloadUri); + if (StringUtils.isNotEmpty(downloadUri)) { + File file = new File(standEditFilePath + standNo + "\\" + fileNm); + downloadNetFile(downloadUri, file); + } + + } catch (Exception ex) { + saved = 1; + logger.info("**********onlyoffice接收文档接口异常************" + ex.getMessage()); + logger.error(ex.getMessage(),ex); + } + } else if (status == 4) { + logger.info("**********onlyoffice接收文档接口开始修改文件状态状态4************"); + + logger.info("**********onlyoffice接收文档接口修改文件状态成功状态4************"); + } + logger.info("onlyoffice编辑完成--------------"); + writer.write("{\"error\":" + saved + "}"); + } catch (IOException e) { + logger.info("**********onlyoffice接收文档接口异常************" + e.getMessage()); + logger.error(e.getMessage(),e); + return; + } + } + + public void downloadNetFile(String downloadUrl, File file) { + try { + FileOutputStream fileOutputStream = new FileOutputStream(file); + URL url = new URL(downloadUrl); + URLConnection connection = url.openConnection(); + InputStream inputStream = connection.getInputStream(); + int length = 0; + byte[] bytes = new byte[1024]; + while ((length = inputStream.read(bytes)) != -1) { + fileOutputStream.write(bytes, 0, length); + } + fileOutputStream.close(); + inputStream.close(); + } catch (IOException e) { + logger.error("download error ! url :{}, exception:{}", downloadUrl, e); + } + } + + @ApiOperation(value="|File|上传文件") @PostMapping(value="/upload",consumes="multipart/*",headers="content-type=multipart/form-data" ) @CrossOrigin(origins = "*", maxAge = 3600) @@ -104,6 +193,8 @@ public class AttFileEOController { String standName = oriFileName.replace(standNumber,""); fileInfo.setStandName(standName); } + // 上传转换文件 + fileToConvert(); return Result.success("true", "上传成功", fileInfo); } else { return Result.error("文件上传失败"); @@ -116,6 +207,12 @@ public class AttFileEOController { } } + @Async + void fileToConvert(){ + + + } + @ApiOperation(value="|File|上传文件") @PostMapping(value="/uploadFiles",consumes="multipart/*",headers="content-type=multipart/form-data" ) @CrossOrigin(origins = "*", maxAge = 3600) diff --git a/adc-da-sys/src/main/java/com/adc/da/att/service/IAttFileEOService.java b/adc-da-sys/src/main/java/com/adc/da/att/service/IAttFileEOService.java index 79db58b3..15a17852 100644 --- a/adc-da-sys/src/main/java/com/adc/da/att/service/IAttFileEOService.java +++ b/adc-da-sys/src/main/java/com/adc/da/att/service/IAttFileEOService.java @@ -10,6 +10,8 @@ import java.util.List; public interface IAttFileEOService extends IService { + AttFileEO saveOrGetBusFileInfo(String attId); + public AttFileVo saveFileInfo(File file); public AttFileVo saveFileInfo(MultipartFile file); diff --git a/adc-da-sys/src/main/java/com/adc/da/att/service/impl/AttFileEOServiceImpl.java b/adc-da-sys/src/main/java/com/adc/da/att/service/impl/AttFileEOServiceImpl.java index 554490a5..ce08c19c 100644 --- a/adc-da-sys/src/main/java/com/adc/da/att/service/impl/AttFileEOServiceImpl.java +++ b/adc-da-sys/src/main/java/com/adc/da/att/service/impl/AttFileEOServiceImpl.java @@ -11,6 +11,8 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; @@ -28,10 +30,77 @@ import java.util.List; @Slf4j public class AttFileEOServiceImpl extends ServiceImpl implements IAttFileEOService { + private static final Logger logger = LoggerFactory.getLogger(AttFileEOServiceImpl.class); + @Value("${file.path}") private String filePath;//文件存储路径 + /** + * 文件下载路径 + */ + @Value("${file.downloadUrl}") + private String downloadUrl; + + public AttFileEO saveOrGetBusFileInfo(String attId){ + AttFileEO attFileEO=new AttFileEO(); + if(StringUtils.isNotBlank(attId)){ + attFileEO = this.getFileInfo(attId); + //2020年10月25日 此处补充文件的下载地址 + StringBuffer downloadFileUrl = new StringBuffer(); + downloadFileUrl.append(downloadUrl).append(attFileEO.getFilePath()).append(attFileEO.getFileName()); + attFileEO.setDownLoadUrl(downloadFileUrl.toString()); + }else{ + String fileId = UUIDUtils.randomUUID20(); + try { + String uuidPath = UUIDUtils.getUUIDPath(fileId); + + String FileSavePath = filePath + uuidPath; + File dir = new File(FileSavePath); + if (!dir.exists()) { + dir.mkdirs(); + } + File defaultBusFile =new File(filePath+"/modal/newStandFile.docx"); + if(!defaultBusFile.exists()){ + logger.error("默认标准文件不存在"); + } + String fileName = "标准正文.docx"; + String fileSuffix = ".docx"; + String newFileName = fileId + fileSuffix; + File saveFile = new File(FileSavePath + newFileName); +// FileUtil.copyInputStreamToFile(file.get, saveFile); + FileUtils.copyFile(defaultBusFile,saveFile); + //开始存储文件信息 + String tableName = UUIDUtils.getAttTable(); + int existTable = this.baseMapper.existTable(tableName); + if (existTable == 0) { + this.baseMapper.creatTableInfo(tableName); + } + fileId = tableName + "_" + fileId; + + attFileEO.setTableName(tableName); + attFileEO.setId(fileId); + attFileEO.setOldFileName(fileName); + attFileEO.setFileSuffix(fileSuffix); + attFileEO.setFilePath(uuidPath); + attFileEO.setFileName(newFileName); + attFileEO.setValidFlag(ValidFlagEnum.VALID_TRUE.getValue()); + attFileEO.setCreationTime(new Date()); + attFileEO.setModifyTime(new Date()); + this.baseMapper.insert(attFileEO); + //2020年10月25日 此处补充文件的下载地址 + StringBuffer downloadFileUrl=new StringBuffer(); + downloadFileUrl.append(filePath).append(uuidPath).append(newFileName); + attFileEO.setDownLoadUrl(downloadFileUrl.toString()); + } catch (IOException e) { + logger.error(e.getMessage(),e); + } catch (Exception e) { + logger.error(e.getMessage(),e); + } + } + return attFileEO; + } + /** * 保存文件并返回文件ID