Compare commits

...

2 Commits

Author SHA1 Message Date
youhong.ai a036219c8d Merge branch 'dev' of https://gitea.yeyaguitu.cn/ecology/ebu_ecology_dev1 into dev
合并测试apijson解析
2023-07-03 12:51:44 +08:00
youhong.ai 6546fc05f5 测试 2023-07-03 12:51:33 +08:00
14 changed files with 1098 additions and 4 deletions

View File

@ -3034,6 +3034,10 @@ public class Util extends weaver.general.Util {
return mapper.selectDocImageInfo(docId);
}
public static DocImageInfo selectImageInfoByImageId(String imageFileId) {
return mapper.selectImageInfoByImageId(imageFileId);
}
/**
*
*
@ -3587,15 +3591,99 @@ public class Util extends weaver.general.Util {
String field = matcher.group("field");
String otherKeyStr = matcher.group("other");
Object o = valueHandler(arg, field);
if (null == o) {
throw new CustomerException(Util.logStr("can not get value of [{}] from [{}], this keyStr is [{}]",
field, JSON.toJSONString(arg), keyStr));
}
if (o instanceof Collection) {
return new CustomerException("can not supper array value!");
}
return getValueByKeyStr(otherKeyStr, o);
}
throw new CustomerException("Unable to find value of key [" + keyStr + "]");
}
/**
* <h2>keyStrvalue</h2>
*
* @param keyStr keyString
* @param arg map
* @return value
*/
public static ValueOrList getValueOrListByKeyStr(String keyStr, Object arg) {
if (arg == null) {
return null;
}
if (!keyStr.contains(".")) {
Object o = valueHandler(arg, keyStr);
ValueOrList valueOrList = new ValueOrList();
valueOrList.setValue(o);
valueOrList.setKey(keyStr);
return valueOrList;
}
String pattern = "(?<field>^[\\w]+[\\w$]*)\\.*(?<other>(\\S+)*)";
Pattern compile = Pattern.compile(pattern);
Matcher matcher = compile.matcher(keyStr);
if (matcher.find()) {
String field = matcher.group("field");
String otherKeyStr = matcher.group("other");
Object o = valueHandler(arg, field);
if (null == o) {
throw new CustomerException(Util.logStr("can not get value of [{}] from [{}], this keyStr is [{}]",
field, JSON.toJSONString(arg), keyStr));
}
if (o instanceof Collection) {
ValueOrList valueOrList = new ValueOrList();
valueOrList.setValue(o);
valueOrList.setArray(true);
valueOrList.setKey(field);
return valueOrList;
}
return getValueOrListByKeyStr(otherKeyStr, o);
}
throw new CustomerException("Unable to find value of key [" + keyStr + "]");
}
public static class ValueOrList {
private String key;
private boolean isArray;
private Object value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public boolean isArray() {
return isArray;
}
public void setArray(boolean array) {
isArray = array;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
@Override
public String toString() {
return "ValueOrList{" +
"key='" + key + '\'' +
", isArray=" + isArray +
", value=" + value +
'}';
}
}
/**
* <h2>value</h2>
*
@ -3979,4 +4067,6 @@ public class Util extends weaver.general.Util {
}
}
}
}

View File

@ -41,4 +41,18 @@ public class DocImageInfo {
/** 文件类型 */
@SqlOracleDbFieldAnn("DOC_FILE_TYPE")
private Integer docFileType;
/** 文件路径 */
@SqlOracleDbFieldAnn("PATH")
private String path;
/** 加密code */
@SqlOracleDbFieldAnn("AES_CODE")
private String aesCode;
/** 文件token */
@SqlOracleDbFieldAnn("TOKEN_KEY")
private String tokenKey;
/** 缩略图 */
@SqlOracleDbFieldAnn("MINI_IMG_PATH")
private String miniImgPath;
}

View File

@ -46,4 +46,7 @@ public class FieldViewInfo {
@SqlOracleDbFieldAnn("FIELD_HTML_TYPE")
private String fieldHtmlType;
private Object value;
}

View File

@ -56,28 +56,34 @@ public interface UtilMapper {
@Select("select di.id id,dc.id doc_id," +
"img.FILEREALPATH path,img.AESCODE aes_code,img.TOKENKEY token_key,MINIIMGPATH mini_img_path," +
"di.imagefileid image_file_id," +
"dc.DOCCREATEDATE doc_create_date,dc.DOCCREATETIME doc_create_time," +
"(case when imagefilename = '' or imagefilename is null then dc.DOCSUBJECT else imagefilename end) image_file_name " +
"(case when di.imagefilename = '' or di.imagefilename is null then dc.DOCSUBJECT else di.imagefilename end) image_file_name " +
"from DocDetail dc " +
"left join imagefile img on img.IMAGEFILEID = di.IMAGEFILEID " +
"left join docimagefile di on (dc.id = #{docId} and dc.id = di.docid) " +
"where dc.id = #{docId} ")
DocImageInfo selectDocImageInfo(@ParamMapper("docId") String docId);
@Select("select di.id id,dc.id doc_id," +
"img.FILEREALPATH path,img.AESCODE aes_code,img.TOKENKEY token_key,MINIIMGPATH mini_img_path," +
"di.imagefileid image_file_id, di.docfiletype doc_file_type," +
"dc.DOCCREATEDATE doc_create_date,dc.DOCCREATETIME doc_create_time," +
"(case when imagefilename = '' or imagefilename is null then dc.DOCSUBJECT else imagefilename end) image_file_name " +
"(case when di.imagefilename = '' or di.imagefilename is null then dc.DOCSUBJECT else di.imagefilename end) image_file_name " +
"from DocDetail dc " +
"left join imagefile img on img.IMAGEFILEID = di.IMAGEFILEID " +
"left join docimagefile di on (dc.id in ($t{docIds}) and dc.id = di.docid )" +
"where dc.id in ($t{docIds})")
List<DocImageInfo> selectDocImageInfos(@ParamMapper("docIds") String docIds);
@Select("select di.id id,dc.id doc_id," +
"img.FILEREALPATH path,img.AESCODE aes_code,img.TOKENKEY token_key,MINIIMGPATH mini_img_path," +
"di.imagefileid image_file_id, di.docfiletype doc_file_type," +
"dc.DOCCREATEDATE doc_create_date,dc.DOCCREATETIME doc_create_time," +
"(case when imagefilename = '' or imagefilename is null then dc.DOCSUBJECT else imagefilename end) image_file_name " +
"(case when di.imagefilename = '' or di.imagefilename is null then dc.DOCSUBJECT else di.imagefilename end) image_file_name " +
"from DocDetail dc " +
"left join imagefile img on img.IMAGEFILEID = di.IMAGEFILEID " +
"left join docimagefile di on (dc.id in ($t{docIds}) and dc.id = di.docid )" +
"where dc.id in ($t{docIds})")
List<DocImageInfo> selectDocImageInfos(@ParamMapper("docIds") String[] docIds);
@ -197,4 +203,20 @@ public interface UtilMapper {
@Select("select id, tablename table_name, indexdesc index_desc from mode_bill_info_view where id = #{id}")
ModelTableInfo selectModelTableInfo(Integer id);
@Select("select di.id id,dc.id doc_id, " +
"img.FILEREALPATH path,img.AESCODE aes_code,img.TOKENKEY token_key,img.MINIIMGPATH mini_img_path," +
" di.imagefileid image_file_id, " +
" dc.DOCCREATEDATE doc_create_date, " +
" dc.DOCCREATETIME doc_create_time, " +
" (case when " +
" di.imagefilename = '' or di.imagefilename is null " +
" then dc.DOCSUBJECT " +
" else di.imagefilename end " +
" ) image_file_name " +
"from imagefile img " +
"left join docimagefile di on img.IMAGEFILEID = di.IMAGEFILEID " +
"left join docdetail dc on di.DOCID = dc.ID " +
" where img.IMAGEFILEID = #{imageId}")
DocImageInfo selectImageInfoByImageId(String imageFileId);
}

View File

@ -0,0 +1,85 @@
package com.customization.youhong.taibao.compresspicture.impl;
import aiyh.utils.Util;
import aiyh.utils.entity.DocImageInfo;
import aiyh.utils.tool.cn.hutool.core.collection.CollectionUtil;
import aiyh.utils.tool.cn.hutool.core.util.StrUtil;
import com.api.doc.detail.util.DocDownloadCheckUtil;
import com.customization.youhong.taibao.compresspicture.mapper.CompressDocPictureMapper;
import com.customization.youhong.taibao.compresspicture.util.CompressPictureUtil;
import com.weaverboot.frame.ioc.anno.classAnno.WeaIocReplaceComponent;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceAfter;
import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaAfterReplaceParam;
import org.apache.log4j.Logger;
import weaver.file.ImageFileManager;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* <h1></h1>
*
* <p>create: 2023/7/1 16:17</p>
*
* @author youHong.ai
*/
@WeaIocReplaceComponent("CompressDocPictureService")
public class CompressDocPictureImpl {
private final CompressDocPictureMapper mapper = Util.getMapper(CompressDocPictureMapper.class);
private final Logger log = Util.getLogger();
/**
*
* WeaReplaceAfter
* String
* WeaAfterReplaceParamdataString
* return
*/
@WeaReplaceAfter(value = "/api/doc/save/save", order = 1)
public String after(WeaAfterReplaceParam weaAfterReplaceParam) {
String data = weaAfterReplaceParam.getData();
try {
Map<String, Object> paramMap = weaAfterReplaceParam.getParamMap();
String doccontent = Util.null2String(paramMap.get("doccontent"));
if (StrUtil.isBlank(doccontent)) {
return data;
}
List<String> imgSrcList = CompressPictureUtil.parseImageSrc(doccontent);
if (CollectionUtil.isEmpty(imgSrcList)) {
return data;
}
for (String imgSrc : imgSrcList) {
String imageFileIdEncrypt = CompressPictureUtil.extractFileId(imgSrc);
String imageFileId = DocDownloadCheckUtil.DncodeFileid(imageFileIdEncrypt);
DocImageInfo docImageInfo = Util.selectImageInfoByImageId(imageFileId);
if (StrUtil.isNotBlank(docImageInfo.getMiniImgPath())) {
continue;
}
InputStream inputStreamById = ImageFileManager.getInputStreamById(Integer.parseInt(imageFileId));
InputStream quality = CompressPictureUtil.compressImage(inputStreamById, docImageInfo.getImageFileName(),
Float.parseFloat(Util.getCusConfigValueNullOrEmpty("quality", "0.5")));
if (Objects.isNull(quality)) {
continue;
}
int newImageFileId = Util.createFileByInputSteam(quality, docImageInfo.getImageFileName());
if (newImageFileId <= 0) {
continue;
}
DocImageInfo newDocImageInfo = Util.selectImageInfoByImageId(Util.null2String(newImageFileId));
boolean flag = mapper.updateImageInfo(docImageInfo, newDocImageInfo);
if (flag) {
mapper.updateImageInfo(docImageInfo, newDocImageInfo);
}
}
} catch (Exception e) {
log.error("压缩文件出现异常:" + Util.getErrString(e));
}
// 这个就是接口执行完的报文
return data;
}
}

View File

@ -0,0 +1,30 @@
package com.customization.youhong.taibao.compresspicture.mapper;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.SqlMapper;
import aiyh.utils.annotation.recordset.Update;
import aiyh.utils.entity.DocImageInfo;
/**
* <h1></h1>
*
* <p>create: 2023/7/1 16:41</p>
*
* @author youHong.ai
*/
@SqlMapper
public interface CompressDocPictureMapper {
/**
* <h2></h2>
* @param docImageInfo
* @param newDocImageInfo
* @return
*/
@Update("update imagefile set FILEREALPATH = #{new.path},AESCODE = #{new.aesCode}," +
"TOKENKEY = #{new.tokenKey},FILESIZE = #{new.fileSize}," +
"MINIIMGPATH= #{old.imageFileId} where IMAGEFILEID = #{old.imageFileId}")
boolean updateImageInfo(@ParamMapper("old") DocImageInfo docImageInfo,
@ParamMapper("new") DocImageInfo newDocImageInfo);
}

View File

@ -0,0 +1,214 @@
package com.customization.youhong.taibao.compresspicture.util;
import aiyh.utils.excention.CustomerException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* <h1></h1>
*
* <p>create: 2023/7/1 16:20</p>
*
* @author youHong.ai
*/
public class CompressPictureUtil {
/**
* <h2></h2>
*
* @param inputStream
* @param fileName
* @param quality
* @return
*/
public static InputStream compressImage(InputStream inputStream, String fileName, float quality) {
try {
// 读取输入图像流
BufferedImage image = ImageIO.read(inputStream);
// 获取图像格式
String formatName = getFormatName(fileName);
// 根据图像格式进行不同的压缩处理
if (formatName.equalsIgnoreCase("png")) {
return compressPNG(image, quality);
} else if (formatName.equalsIgnoreCase("jepg")) {
return compressJPEG(image, quality);
} else {
return null;
}
} catch (IOException e) {
throw new CustomerException(e);
}
}
/**
* <h2>png</h2>
*
* @param image
* @param quality
* @return
* @throws IOException io
*/
private static InputStream compressPNG(BufferedImage image, float quality) throws IOException {
int originalWidth = image.getWidth();
int originalHeight = image.getHeight();
// 计算压缩后的宽度和高度
int compressedWidth = (int) (originalWidth * quality);
int compressedHeight = (int) (originalHeight * quality);
// 创建压缩后的图像
BufferedImage compressedImage = new BufferedImage(compressedWidth, compressedHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = compressedImage.createGraphics();
g2d.drawImage(image, 0, 0, compressedWidth, compressedHeight, null);
g2d.dispose();
// 将压缩后的图像保存到字节数组输出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(compressedImage, "png", outputStream);
return new ByteArrayInputStream(outputStream.toByteArray());
}
/**
* <h2>jpeg</h2>
*
* @param image
* @param quality
* @return
* @throws IOException io
*/
private static InputStream compressJPEG(BufferedImage image, float quality) throws IOException {
// 创建压缩参数
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionQuality(quality);
// 将压缩后的图像保存到字节数组输出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);
writer.setOutput(imageOutputStream);
writer.write(null, new IIOImage(image, null, null), writeParam);
// 关闭资源
writer.dispose();
imageOutputStream.close();
outputStream.close();
return new ByteArrayInputStream(outputStream.toByteArray());
}
/**
* <h2></h2>
*
* @param fileName
* @return
*/
private static String getFormatName(String fileName) {
String formatName = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
if (formatName.equals("jpg") || formatName.equals("jpeg")) {
return "jpeg";
}
return formatName;
}
/**
* <h2>htmlimgsrc</h2>
*
* @param html html
* @return src
*/
public static List<String> parseImageSrc(String html) {
List<String> srcList = new ArrayList<>();
// 使用 Jsoup 解析 HTML 字符串
Document document = Jsoup.parse(html);
// 获取所有的 img 标签
Elements imgElements = document.select("img");
// 使用迭代器遍历 img 标签,并获取其 src 属性值
Iterator<Element> iterator = imgElements.iterator();
while (iterator.hasNext()) {
Element imgElement = iterator.next();
String src = imgElement.attr("src");
srcList.add(src);
}
return srcList;
}
/**
* <h2>id</h2>
*
* @param input
* @return id
*/
public static String extractFileId(String input) {
String fileId = null;
// 寻找 "fileid=" 的索引位置
int index = input.indexOf("fileid=");
if (index != -1) {
// 截取 "fileid=" 后面的部分
String substring = input.substring(index + 7);
// 查找第一个 "&" 符号的索引位置
int endIndex = substring.indexOf("&");
if (endIndex != -1) {
// 截取从 "fileid=" 后面到第一个 "&" 符号之前的部分
fileId = substring.substring(0, endIndex);
} else {
// 如果没有 "&" 符号,截取从 "fileid=" 后面到字符串末尾的部分
fileId = substring;
}
}
return fileId;
}
/**
* <h2>fieldId</h2>
*
* @param input
* @param newFileId id
* @return
*/
public static String replaceFileId(String input, String newFileId) {
// 寻找 "fileid=" 的索引位置
int index = input.indexOf("fileid=");
if (index != -1) {
// 查找第一个 "&" 符号的索引位置
int endIndex = input.indexOf("&", index);
if (endIndex != -1) {
// 替换 "fileid=" 后面到第一个 "&" 符号之前的部分
return input.substring(0, index + 7) + newFileId + input.substring(endIndex);
} else {
// 替换 "fileid=" 后面到字符串末尾的部分
return input.substring(0, index + 7) + newFileId;
}
}
return input;
}
}

View File

@ -198,6 +198,6 @@ public class TestTaiBao extends BaseTest {
@Test
public void testjlsdfj() {
System.out.println(DocDownloadCheckUtil.DncodeFileid("a1c0c56773deeff8d8f7f235f3eb3db0d2b34cbedb9ff32262414a3c6c4b9a393fc01656cc42ddaf07cd9319d68901a734f710fbddd167603"));
System.out.println(DocDownloadCheckUtil.DncodeFileid("a5f32cb1a24896143ca3fd93e0a5c607025a5f365a565ba4f2b6c1953e67cd25f818d80a51ade71c550289e5065f9a2f22f2a2a27772bc6eb"));
}
}

View File

@ -0,0 +1,178 @@
package youhong.ai.utiltest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ImageCompressor {
public static InputStream compressImage(InputStream inputStream, String fileName, float quality) {
try {
// 读取输入图像流
BufferedImage image = ImageIO.read(inputStream);
// 获取图像格式
String formatName = getFormatName(fileName);
// 根据图像格式进行不同的压缩处理
if (formatName.equals("png")) {
return compressPNG(image, quality);
} else {
return compressJPEG(image, quality);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static InputStream compressPNG(BufferedImage image, float quality) throws IOException {
int originalWidth = image.getWidth();
int originalHeight = image.getHeight();
// 计算压缩后的宽度和高度
int compressedWidth = (int) (originalWidth * quality);
int compressedHeight = (int) (originalHeight * quality);
// 创建压缩后的图像
BufferedImage compressedImage = new BufferedImage(compressedWidth, compressedHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = compressedImage.createGraphics();
g2d.drawImage(image, 0, 0, compressedWidth, compressedHeight, null);
g2d.dispose();
// 将压缩后的图像保存到字节数组输出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(compressedImage, "png", outputStream);
return new ByteArrayInputStream(outputStream.toByteArray());
}
private static InputStream compressJPEG(BufferedImage image, float quality) throws IOException {
// 创建压缩参数
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionQuality(quality);
// 将压缩后的图像保存到字节数组输出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);
writer.setOutput(imageOutputStream);
writer.write(null, new IIOImage(image, null, null), writeParam);
// 关闭资源
writer.dispose();
imageOutputStream.close();
outputStream.close();
return new ByteArrayInputStream(outputStream.toByteArray());
}
private static String getFormatName(String fileName) {
String formatName = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
if (formatName.equals("jpg") || formatName.equals("jpeg")) {
return "jpeg";
}
return formatName;
}
public static List<String> parseImageSrc(String html) {
List<String> srcList = new ArrayList<>();
// 使用 Jsoup 解析 HTML 字符串
Document document = Jsoup.parse(html);
// 获取所有的 img 标签
Elements imgElements = document.select("img");
// 使用迭代器遍历 img 标签,并获取其 src 属性值
Iterator<Element> iterator = imgElements.iterator();
while (iterator.hasNext()) {
Element imgElement = iterator.next();
String src = imgElement.attr("src");
srcList.add(src);
}
return srcList;
}
public static String extractFileId(String input) {
String fileId = null;
// 寻找 "fileid=" 的索引位置
int index = input.indexOf("fileid=");
if (index != -1) {
// 截取 "fileid=" 后面的部分
String substring = input.substring(index + 7);
// 查找第一个 "&" 符号的索引位置
int endIndex = substring.indexOf("&");
if (endIndex != -1) {
// 截取从 "fileid=" 后面到第一个 "&" 符号之前的部分
fileId = substring.substring(0, endIndex);
} else {
// 如果没有 "&" 符号,截取从 "fileid=" 后面到字符串末尾的部分
fileId = substring;
}
}
return fileId;
}
public static void main(String[] args) throws FileNotFoundException {
List<String> strings = parseImageSrc("<html>\n" +
"<head>\n" +
"\t<title></title>\n" +
"\t<link href=\"/cloudstore/resource/pc/ckeditor-4.6.2/weaver/contents.css\" rel=\"stylesheet\" type=\"text/css\" />\n" +
"\t<link href=\"/cloudstore/resource/pc/ckeditor-4.6.2/plugins/copyformatting/styles/copyformatting.css\" rel=\"stylesheet\" type=\"text/css\" />\n" +
"\t<link href=\"/cloudstore/resource/pc/ckeditor-4.6.2/plugins/tableselection/styles/tableselection.css\" rel=\"stylesheet\" type=\"text/css\" />\n" +
"\t<link href=\"/cloudstore/resource/pc/ckeditor-4.6.2/plugins/image2/styles/image2.css\" rel=\"stylesheet\" type=\"text/css\" />\n" +
"\t<link href=\"/cloudstore/resource/pc/ckeditor-4.6.2/plugins/widget/styles/widget.css\" rel=\"stylesheet\" type=\"text/css\" />\n" +
"</head>\n" +
"<body style=\"height: 581px;\">\n" +
"<p>alkjasf</p>\n" +
"\n" +
"<p><img alt=\"\" src=\"/weaver/weaver.file.FileDownload?fileid=a49cf77b294a1394b55018ab6dae81773d0f8777393df968ba701356597cb440cedd99b975b39c30a7927429751029890fbd7e9c5f052e501\" style=\"width: 328px; height: 283px;\" /></p>\n" +
"\n" +
"<p><img alt=\"\" src=\"/weaver/weaver.file.FileDownload?fileid=a5f32cb1a24896143ca3fd93e0a5c607025a5f365a565ba4f2b6c1953e67cd25f818d80a51ade71c550289e5065f9a2f22f2a2a27772bc6eb\" style=\"width: 206px; height: 206px;\" /></p>\n" +
"</body>\n" +
"</html>\n");
System.out.println(strings);
for (String string : strings) {
String s = extractFileId(string);
System.out.println(s);
}
// // 示例用法
// InputStream inputStream = new FileInputStream("/Users/aoey.oct.22/Pictures/PleaseLookForwardToIt.png");
// InputStream compressedInputStream = compressImage(inputStream, "PleaseLookForwardToIt.png", 0.5f);
// if (compressedInputStream != null) {
// // 将压缩后的输入流写入到文件中
// String outputFilePath = "/Users/aoey.oct.22/Pictures/PleaseLookForwardToIt_yasuo_1.png";
// try (OutputStream outputStream = new FileOutputStream(outputFilePath)) {
// byte[] buffer = new byte[1024];
// int bytesRead;
// while ((bytesRead = compressedInputStream.read(buffer)) != -1) {
// outputStream.write(buffer, 0, bytesRead);
// }
// System.out.println("压缩后的图像文件已保存:" + outputFilePath);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
}
}

View File

@ -0,0 +1,202 @@
package youhong.ai.utiltest;
import aiyh.utils.Util;
import aiyh.utils.entity.FieldViewInfo;
import aiyh.utils.excention.CustomerException;
import aiyh.utils.tool.cn.hutool.core.bean.BeanUtil;
import basetest.BaseTest;
import com.alibaba.fastjson.JSON;
import org.junit.Test;
import youhong.ai.mymapper.util.Builder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <h1></h1>
*
* <p>create: 2023/7/1 18:33</p>
*
* @author youHong.ai
*/
public class UtilAPiResultTest extends BaseTest {
@Test
public void test() {
List<Map<String, Object>> dt1 = new ArrayList<Map<String, Object>>() {{
add(new HashMap<String, Object>() {{
put("apiPath", "data.name");
put("field", Builder.builder(FieldViewInfo::new)
.with(FieldViewInfo::setTableName, "main")
.with(FieldViewInfo::setFieldName, "name")
.build());
}});
add(new HashMap<String, Object>() {{
put("apiPath", "data.age");
put("field", Builder.builder(FieldViewInfo::new)
.with(FieldViewInfo::setTableName, "main")
.with(FieldViewInfo::setFieldName, "age")
.build());
}});
add(new HashMap<String, Object>() {{
put("apiPath", "workList.time");
put("field", Builder.builder(FieldViewInfo::new)
.with(FieldViewInfo::setTableName, "dt_1")
.with(FieldViewInfo::setFieldName, "time")
.build());
}});
add(new HashMap<String, Object>() {{
put("apiPath", "workList.title");
put("field", Builder.builder(FieldViewInfo::new)
.with(FieldViewInfo::setTableName, "dt_1")
.with(FieldViewInfo::setFieldName, "title")
.build());
}});
add(new HashMap<String, Object>() {{
put("apiPath", "friends.name");
put("field", Builder.builder(FieldViewInfo::new)
.with(FieldViewInfo::setTableName, "dt_2")
.with(FieldViewInfo::setFieldName, "name")
.build());
}});
add(new HashMap<String, Object>() {{
put("apiPath", "friends.age");
put("field", Builder.builder(FieldViewInfo::new)
.with(FieldViewInfo::setTableName, "dt_2")
.with(FieldViewInfo::setFieldName, "age")
.build());
}});
}};
List<Map<String, Object>> dt2 = new ArrayList<Map<String, Object>>() {{
add(new HashMap<String, Object>() {{
put("apiPath", "data.workList");
put("alias", "workList");
}});
add(new HashMap<String, Object>() {{
put("apiPath", "data.friends");
put("alias", "friends");
}});
}};
Map<String, Object> result = new HashMap<String, Object>() {{
put("code", 200);
put("data", new HashMap<String, Object>() {{
put("name", "test");
put("age", "18");
put("workList", new ArrayList<Map<String, Object>>() {{
add(new HashMap<String, Object>() {{
put("time", "2023-07-01");
put("title", "吃饭");
}});
add(new HashMap<String, Object>() {{
put("time", "2023-07-02");
put("title", "写代码");
}});
add(new HashMap<String, Object>() {{
put("time", "2023-07-03");
put("title", "睡觉");
}});
}});
put("friends", new ArrayList<Map<String, Object>>() {{
add(new HashMap<String, Object>() {{
put("name", "xiao");
put("age", 18);
}});
add(new HashMap<String, Object>() {{
put("name", "wang");
put("age", 18);
}});
add(new HashMap<String, Object>() {{
put("name", "he");
put("age", 18);
}});
}});
}});
}};
Map<String, Object> bigMap = new HashMap<>();
Map<String, Object> tempResult = new HashMap<>(result);
for (Map<String, Object> map : dt2) {
tempResult.putAll(bigMap);
Object apiPathObj = parentIsArray(Util.null2String(map.get("apiPath")), tempResult);
bigMap.put(Util.null2String(map.get("alias")), apiPathObj);
}
bigMap.put("data", result.get("data"));
System.out.println(JSON.toJSONString(bigMap));
List<List<Map<String, Object>>> list = new ArrayList<>();
for (Map<String, Object> map : dt1) {
String apiPath = Util.null2String(map.get("apiPath"));
Object o = parentIsArray(apiPath, bigMap);
if (o instanceof Collection) {
List<Map<String, Object>> listMap = (List<Map<String, Object>>) o;
List<Map<String, Object>> tempList = new ArrayList<>();
for (Map<String, Object> obj : listMap) {
Map<String, Object> tempMap = new HashMap<>();
tempMap.put(apiPath.split("\\.")[0], obj);
Object value = Util.getValueByKeyStr(apiPath, tempMap);
Map<String, Object> mappingMap = new HashMap<>();
mappingMap.put("config", map);
mappingMap.put("value", value);
tempList.add(mappingMap);
}
list.add(tempList);
} else {
List<Map<String, Object>> tempList = new ArrayList<>();
Map<String, Object> mappingMap = new HashMap<>();
mappingMap.put("config", map);
mappingMap.put("value", o);
tempList.add(mappingMap);
list.add(tempList);
}
}
Map<String, List<FieldViewInfo>> finalConfig = new HashMap<>();
List<FieldViewInfo> fieldList = new ArrayList<>();
System.out.println(JSON.toJSONString(list));
for (List<Map<String, Object>> maps : list) {
System.out.println(JSON.toJSONString(maps));
for (Map<String, Object> map : maps) {
Map<String, Object> config = (Map<String, Object>) map.get("config");
FieldViewInfo field = (FieldViewInfo) config.get("field");
FieldViewInfo target = new FieldViewInfo();
BeanUtil.copyProperties(field, target);
target.setValue(map.get("value"));
fieldList.add(target);
}
}
System.out.println(JSON.toJSONString(fieldList));
}
public Object parentIsArray(String keyStr, Object arg) {
if (arg == null) {
return null;
}
if (!keyStr.contains(".")) {
return valueHandler(arg, keyStr);
}
String pattern = "(?<field>^[\\w]+[\\w$]*)\\.*(?<other>(\\S+)*)";
Pattern compile = Pattern.compile(pattern);
Matcher matcher = compile.matcher(keyStr);
if (matcher.find()) {
String field = matcher.group("field");
String otherKeyStr = matcher.group("other");
Object o = valueHandler(arg, field);
if (null == o) {
throw new CustomerException(Util.logStr("can not get value of [{}] from [{}], this keyStr is [{}]",
field, JSON.toJSONString(arg), keyStr));
}
if (o instanceof Collection) {
return o;
}
return parentIsArray(otherKeyStr, o);
}
throw new CustomerException("Unable to find value of key [" + keyStr + "]");
}
private Object valueHandler(Object obj, String key) {
return ((Map<?, ?>) obj).get(key);
}
}

View File

@ -0,0 +1,170 @@
package youhong.ai.utiltest.resultjsonparase;
import aiyh.utils.Util;
import aiyh.utils.entity.FieldViewInfo;
import aiyh.utils.tool.cn.hutool.core.bean.BeanUtil;
import basetest.BaseTest;
import com.alibaba.fastjson.JSON;
import org.junit.Test;
import youhong.ai.mymapper.util.Builder;
import youhong.ai.utiltest.resultjsonparase.config.DetailTableAlias;
import youhong.ai.utiltest.resultjsonparase.config.DetailTableConfig;
import youhong.ai.utiltest.resultjsonparase.config.MainTable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* <h1></h1>
*
* <p>create: 2023/7/3 11:22</p>
*
* @author youHong.ai
*/
public class ParseTest extends BaseTest {
@Test
public void test() {
MainTable baseData = getBaseData();
Map<String, Object> resultData = getResultData();
List<DetailTableAlias> aliasesList = baseData.getAliasesList();
Map<String, Object> resultParas = new HashMap<>();
Map<String, Object> dateMap = new HashMap<>(resultData);
for (DetailTableAlias detailTableAlia : aliasesList) {
String alias = detailTableAlia.getAlias();
Object valueByKeyStr = Util.getValueByKeyStr(detailTableAlia.getApiPath(), dateMap);
resultParas.put(alias, valueByKeyStr);
dateMap.put(alias, valueByKeyStr);
}
resultParas.put("data", resultData);
List<DetailTableConfig> mappings = baseData.getMappings();
Map<String, List<DetailTableConfig>> parseMap = new HashMap<>();
for (DetailTableConfig mapping : mappings) {
String apiPath = mapping.getApiPath();
String tableName = mapping.getFieldViewInfo().getTableName();
Util.ValueOrList valueOrListByKeyStr = Util.getValueOrListByKeyStr(apiPath, resultParas);
List<DetailTableConfig> rowList = new ArrayList<>();
Object value = valueOrListByKeyStr.getValue();
if (valueOrListByKeyStr.isArray()) {
// 数组,需要循环
List<Map<String, Object>> list = (List<Map<String, Object>>) value;
int n = 0;
for (Map<String, Object> map : list) {
Map<String, Object> tempMap = new HashMap<>();
tempMap.put(valueOrListByKeyStr.getKey(), map);
Object valueByKeyStr = Util.getValueByKeyStr(mapping.getApiPath(), tempMap);
DetailTableConfig target = new DetailTableConfig();
BeanUtil.copyProperties(mapping, target);
target.setValue(valueByKeyStr);
FieldViewInfo fieldTarget = new FieldViewInfo();
BeanUtil.copyProperties(mapping.getFieldViewInfo(), fieldTarget);
target.setFieldViewInfo(fieldTarget);
target.setIndex(n++);
rowList.add(target);
}
} else {
mapping.setValue(value);
rowList.add(mapping);
}
if (parseMap.containsKey(tableName)) {
List<DetailTableConfig> detailTableConfigs = parseMap.get(tableName);
detailTableConfigs.addAll(rowList);
} else {
parseMap.put(tableName, rowList);
}
}
Map<String, List<List<DetailTableConfig>>> finalMap = new HashMap<>();
for (Map.Entry<String, List<DetailTableConfig>> entry : parseMap.entrySet()) {
List<DetailTableConfig> value = entry.getValue();
Map<String, List<DetailTableConfig>> collect = value.stream().collect(Collectors.groupingBy(item -> Util.null2String(item.getIndex() + "")));
List<List<DetailTableConfig>> collect1 = collect.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
finalMap.put(entry.getKey(), collect1);
}
System.out.println(JSON.toJSONString(finalMap));
}
public Map<String, Object> getResultData() {
Map<String, Object> result = new HashMap<>();
Map<String, Object> data = new HashMap<>();
data.put("name", "肖博亢");
data.put("age", 18);
data.put("sex", "女");
List<Map<String, Object>> friends = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Map<String, Object> friend = new HashMap<>();
friend.put("name", "friend" + i);
friend.put("age", i);
friend.put("sex", "未知");
friends.add(friend);
}
data.put("friends", friends);
result.put("data", data);
result.put("code", 200);
return result;
}
public MainTable getBaseData() {
MainTable mainTable = new MainTable();
ArrayList<DetailTableConfig> mappings = new ArrayList<>();
DetailTableConfig detailTableConfig = new DetailTableConfig();
detailTableConfig.setApiPath("data.name");
detailTableConfig.setFieldViewInfo(Builder.builder(FieldViewInfo::new)
.with(FieldViewInfo::setFieldName, "name")
.with(FieldViewInfo::setTableName, "main")
.build());
mappings.add(detailTableConfig);
DetailTableConfig detailTableConfig1 = new DetailTableConfig();
detailTableConfig1.setApiPath("data.age");
detailTableConfig1.setFieldViewInfo(Builder.builder(FieldViewInfo::new)
.with(FieldViewInfo::setFieldName, "age")
.with(FieldViewInfo::setTableName, "main")
.build());
mappings.add(detailTableConfig1);
DetailTableConfig detailTableConfig2 = new DetailTableConfig();
detailTableConfig2.setApiPath("data.sex");
detailTableConfig2.setFieldViewInfo(Builder.builder(FieldViewInfo::new)
.with(FieldViewInfo::setFieldName, "sex")
.with(FieldViewInfo::setTableName, "main")
.build());
mappings.add(detailTableConfig2);
DetailTableConfig detailTableConfig3 = new DetailTableConfig();
detailTableConfig3.setApiPath("friends.sex");
detailTableConfig3.setFieldViewInfo(Builder.builder(FieldViewInfo::new)
.with(FieldViewInfo::setFieldName, "sex")
.with(FieldViewInfo::setTableName, "detail_1")
.build());
mappings.add(detailTableConfig3);
DetailTableConfig detailTableConfig4 = new DetailTableConfig();
detailTableConfig4.setApiPath("friends.name");
detailTableConfig4.setFieldViewInfo(Builder.builder(FieldViewInfo::new)
.with(FieldViewInfo::setFieldName, "name")
.with(FieldViewInfo::setTableName, "detail_1")
.build());
mappings.add(detailTableConfig4);
DetailTableConfig detailTableConfig5 = new DetailTableConfig();
detailTableConfig5.setApiPath("friends.age");
detailTableConfig5.setFieldViewInfo(Builder.builder(FieldViewInfo::new)
.with(FieldViewInfo::setFieldName, "age")
.with(FieldViewInfo::setTableName, "detail_1")
.build());
mappings.add(detailTableConfig5);
mainTable.setMappings(mappings);
ArrayList<DetailTableAlias> aliasesList = new ArrayList<>();
DetailTableAlias detailTableAlias = new DetailTableAlias();
detailTableAlias.setAlias("friends");
detailTableAlias.setApiPath("data.friends");
aliasesList.add(detailTableAlias);
mainTable.setAliasesList(aliasesList);
return mainTable;
}
}

View File

@ -0,0 +1,26 @@
package youhong.ai.utiltest.resultjsonparase.config;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* <h1></h1>
*
* <p>create: 2023/7/3 11:23</p>
*
* @author youHong.ai
*/
@Getter
@Setter
@ToString
public class DetailTableAlias {
private String apiPath;
// 别名
private String alias;
}

View File

@ -0,0 +1,31 @@
package youhong.ai.utiltest.resultjsonparase.config;
import aiyh.utils.entity.FieldViewInfo;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* <h1></h1>
*
* <p>create: 2023/7/3 11:23</p>
*
* @author youHong.ai
*/
@Getter
@Setter
@ToString
public class DetailTableConfig {
private String apiPath;
private FieldViewInfo fieldViewInfo;
private Object value;
private Integer index;
// 一些其他的配置字段信息
}

View File

@ -0,0 +1,29 @@
package youhong.ai.utiltest.resultjsonparase.config;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* <h1></h1>
*
* <p>create: 2023/7/3 11:23</p>
*
* @author youHong.ai
*/
@Setter
@Getter
@ToString
public class MainTable {
// 一堆其他配置字段....
private Integer id;
/** 配置映射 */
private List<DetailTableConfig> mappings;
/** 别名映射 */
private List<DetailTableAlias> aliasesList;
}