Commit 1606ba4f authored by ZWT's avatar ZWT

都删了

parent 6b9652f7
package pps.core.common.pdf;
import com.itextpdf.text.pdf.BaseFont;
import org.apache.commons.codec.binary.Base64;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import sun.misc.BASE64Decoder;
import java.io.*;
import java.util.Map;
public class Html2Pdf {
public static String htmlTopdf(String htmlContent, String fontPath) throws Exception {
ByteArrayOutputStream byteArrayOutputStream = null;
InputStream sbs = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver font = renderer.getFontResolver();
font.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//添加中文识别,这里是设置的宋体,Linux下要换成对应的字体
renderer.setDocumentFromString(htmlContent);
renderer.layout();
renderer.createPDF(byteArrayOutputStream);
renderer.finishPDF();
byte[] buffer = byteArrayOutputStream.toByteArray();
sbs = new ByteArrayInputStream(buffer);
return getBase64FromInputStream(sbs);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
}
}
if (sbs != null) {
try {
sbs.close();
} catch (IOException e) {
}
}
}
return null;
}
public static byte[] htmlToPdfByte(String htmlContent, String fontPath) {
ByteArrayOutputStream byteArrayOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver font = renderer.getFontResolver();
font.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//添加中文识别,这里是设置的宋体,Linux下要换成对应的字体
renderer.setDocumentFromString(htmlContent);
renderer.layout();
renderer.createPDF(byteArrayOutputStream);
renderer.finishPDF();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
}
}
}
return byteArrayOutputStream.toByteArray();
}
public static String getBase64FromInputStream(InputStream in) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new String(Base64.encodeBase64(data));
}
public static void saveBase64strToFile(String base64str, String outPath) {
createFile(new File(outPath));
if (base64str == null) {
return;
}
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(base64str);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(outPath);
out.write(b);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String replaceContent(String htmlContent, Map<String, String> map) {
for (Map.Entry<String, String> entry : map.entrySet()) {
htmlContent = htmlContent.replaceAll(entry.getKey(), entry.getValue());
}
return htmlContent;
}
public static void createFile(File file) {
if (file.exists()) {
System.out.println("File exists");
} else {
System.out.println("File not exists, create it ...");
//getParentFile() 获取上级目录(包含文件名时无法直接创建目录的)
if (!file.getParentFile().exists()) {
System.out.println("not exists");
//创建上级目录
file.getParentFile().mkdirs();
}
try {
//在上级目录里创建文件
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void outFile(InputStream input, String outPath) {
createFile(new File(outPath));
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(input);
out = new BufferedOutputStream(new FileOutputStream(outPath));
int len = -1;
byte[] b = new byte[1024];
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
in.close();
out.close();
} catch (Exception e) {
}
}
}
package pps.core.common.pdf;
import cn.hutool.core.io.file.FileReader;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import gui.ava.html.parser.HtmlParser;
import gui.ava.html.parser.HtmlParserImpl;
import gui.ava.html.renderer.ImageRenderer;
import gui.ava.html.renderer.ImageRendererImpl;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.ResourceUtils;
import sun.misc.BASE64Decoder;
import xstartup.base.util.XDateUtils;
import xstartup.base.util.XStringUtils;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class Itext5HtmlToPDF {
public static void main(String[] args) throws Exception {
String base64 = htmlToPDF("<!DOCTYPE html>\n" +
"<html lang=\"en\">\n" +
"<head>\n" +
"\t<meta charset=\"utf-8\"/>\n" +
"\t<title>PPS</title>\n" +
"\t<style>\n" +
"\t\tbody {\n" +
"\t\t\tfont-family: sans-serif, 'Microsoft Yahei';\n" +
"\t\t}\n" +
"\n" +
"\t\t.container {\n" +
"\t\t/*\twidth: 1240px;\n" +
"\t\t\theight: 1754px;\n" +
"\t\t\tmargin: 0 auto;*/\n" +
"\t\t\tpadding: 16px;\n" +
"\t\t\tbox-sizing: border-box;\n" +
"\t\t\tbackground-color: #ffffff;\n" +
"\t\t\tline-height: 1.5;\n" +
"\t\t\tfont-size: 16px;\n" +
"\t\t\tfont-weight: bold;\n" +
"\t\t}\n" +
"\n" +
"\t\t.container h1 {\n" +
"\t\t\ttext-align: center;\n" +
"\t\t\tline-height: 1;\n" +
"\t\t\tfont-size: 28px;\n" +
"\t\t\tfont-weight: 900;\n" +
"\t\t}\n" +
"\n" +
"\t\t.container .datecode {\n" +
"\t\t\toverflow: hidden;\n" +
"\t\t}\n" +
"\n" +
"\t\t.container .datecode span {\n" +
"\t\t\tfloat: left;\n" +
"\t\t}\n" +
"\n" +
"\t\t.container .datecode span:last-child {\n" +
"\t\t\tfloat: right;\n" +
"\t\t}\n" +
"\t\t.left{\n" +
"\t\t\ttext-align: left;\n" +
"\t\t}\n" +
"\t\ttable {\n" +
"\t\t\twidth: 100%;\n" +
"\t\t\tborder-collapse: collapse;\n" +
"\t\t\tborder-spacing: 0;\n" +
"\t\t}\n" +
"\n" +
"\t\ttable, th, td {\n" +
"\t\t\tline-height: 2;\n" +
"\t\t\tborder: 1px solid #000000;\n" +
"\t\t\ttext-align: center;\n" +
"\t\t\tpadding: 0 5px;\n" +
"\t\t}\n" +
"\n" +
"\t\tth {\n" +
"\t\t\twidth: auto;\n" +
"\t\t\tfont-weight: bold;\n" +
"\t\t}\n" +
"\n" +
"\t\ttd {\n" +
"\t\t\twidth: auto;\n" +
"\t\t}\n" +
"\t</style>\n" +
"</head>\n" +
"<body>\n" +
"<div class=\"container\">\n" +
"\t<h1>国家管网集团联合管道有限责任公司西气东输分公司</h1>\n" +
"\t<h1>天然气计量交接凭证(中卫首站)</h1>\n" +
"\t<div class=\"datecode\">\n" +
"\t\t<span>填写日期:2022-07-07</span>\n" +
"\t\t<span>凭证编号:185--220708</span>\n" +
"\t</div>\n" +
"\t<table cellspacing=\"0\">\n" +
"\t\t<tr>\n" +
"\t\t\t<td class=\"left\" colspan=\"2\">承运单位:国家管网集团联合管道有限责任公司西气东输分公司</td>\n" +
"\t\t\t<td class=\"left\" colspan=\"2\">托运单位:</td>\n" +
"\t\t\t<td class=\"left\" colspan=\"3\">接收单位:江苏华电昆山热电有限公司</td>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td class=\"left\" colspan=\"7\">计量时间:2022年7月5日 08:00 至 2022年7月6日 08:00</td>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<th>计量交接地点</th>\n" +
"\t\t\t<th>流量计位号</th>\n" +
"\t\t\t<th>前日日累(体积量)Nm3</th>\n" +
"\t\t\t<th>前日日累(能量)MJ</th>\n" +
"\t\t\t<th>平均高位发热量MJ/m3</th>\n" +
"\t\t\t<th>计量气量Nm3</th>\n" +
"\t\t\t<th>计量能量MJ</th>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td>中卫首站</td>\n" +
"\t\t\t<td>FM501</td>\n" +
"\t\t\t<td>156140210</td>\n" +
"\t\t\t<td>156140210</td>\n" +
"\t\t\t<td>6436881280</td>\n" +
"\t\t\t<td>11009989685</td>\n" +
"\t\t\t<td>13242421311</td>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td>中卫首站</td>\n" +
"\t\t\t<td>FM501</td>\n" +
"\t\t\t<td>156140210</td>\n" +
"\t\t\t<td>156140210</td>\n" +
"\t\t\t<td>6436881280</td>\n" +
"\t\t\t<td>11009989685</td>\n" +
"\t\t\t<td>13242421311</td>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td>中卫首站</td>\n" +
"\t\t\t<td>FM501</td>\n" +
"\t\t\t<td>156140210</td>\n" +
"\t\t\t<td>156140210</td>\n" +
"\t\t\t<td>6436881280</td>\n" +
"\t\t\t<td>11009989685</td>\n" +
"\t\t\t<td>13242421311</td>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td>中卫首站</td>\n" +
"\t\t\t<td>FM501</td>\n" +
"\t\t\t<td>156140210</td>\n" +
"\t\t\t<td>156140210</td>\n" +
"\t\t\t<td>6436881280</td>\n" +
"\t\t\t<td>11009989685</td>\n" +
"\t\t\t<td>13242421311</td>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td colspan=\"2\">合计交接气量(小写)Nm3</td>\n" +
"\t\t\t<td colspan=\"2\">94010</td>\n" +
"\t\t\t<td>合计交接能量(小写)MJ</td>\n" +
"\t\t\t<td colspan=\"2\">94010</td>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td colspan=\"2\">合计交接气量(大写)Nm3</td>\n" +
"\t\t\t<td colspan=\"2\">玖万肆仟零壹拾标方</td>\n" +
"\t\t\t<td>合计交接能量(大写)MJ</td>\n" +
"\t\t\t<td colspan=\"2\">玖万肆仟零壹拾标方</td>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td>备注:</td>\n" +
"\t\t\t<td colspan=\"6\"></td>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td colspan=\"2\">供气单位(盖章)</td>\n" +
"\t\t\t<td colspan=\"2\" style=\"opacity: 0;\">供气</td>\n" +
"\t\t\t<td>接气单位(盖章)</td>\n" +
"\t\t\t<td colspan=\"2\"></td>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td colspan=\"2\">供气方计量员(签字)</td>\n" +
"\t\t\t<td colspan=\"2\"></td>\n" +
"\t\t\t<td>接气方计量员(签字)</td>\n" +
"\t\t\t<td colspan=\"2\"></td>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td>争议量(+/-):</td>\n" +
"\t\t\t<td colspan=\"6\"></td>\n" +
"\t\t</tr>\n" +
"\t</table>\n" +
"</div>\n" +
"</body>\n" +
"</html>\n" , new HashMap<>());
saveBase64strToFile(base64 , "D:\\pdf\\test"+ new Date().getTime() +".pdf");
}
public static String replaceContent(String htmlContent , Map<String,String> map){
for (Map.Entry<String, String> entry : map.entrySet()) {
htmlContent = htmlContent.replaceAll(entry.getKey() , entry.getValue());
}
return htmlContent;
}
public static ByteArrayOutputStream htmlSaveImage(String htmlContent){
HtmlParser htmlParser = new HtmlParserImpl();
//加载html模版
htmlParser.loadHtml(htmlContent);
//把html写入到图片
ImageRenderer imageRenderer = new ImageRendererImpl(htmlParser);
imageRenderer.setWidth(2048);
imageRenderer.setHeight(1536);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageRenderer.saveImage(byteArrayOutputStream ,true);
return byteArrayOutputStream;
}
public static String imageToPDF(ByteArrayOutputStream imageByte) throws Exception{
Document document = new Document();
//第二步,为该Document创建一个Writer实例:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document , byteArrayOutputStream);
//第三步,打开当前Document
document.open();
//第四步,为当前Document添加内容:
//替换内容
document.newPage(); //在pdf创建一页
Image png1 = Image.getInstance(imageByte.toByteArray()); //通过文件路径获取image
float heigth = png1.getHeight();
float width = png1.getWidth();
int percent = getPercent2(heigth, width);
png1.setAlignment(Image.MIDDLE);
png1.scalePercent(percent + 3);// 表示是原来图像的比例;
document.add(png1);
//第五步,关闭Document
document.close();
byte[] buffer =byteArrayOutputStream.toByteArray();
InputStream sbs = new ByteArrayInputStream(buffer);
return getBase64FromInputStream(sbs);
}
public static String htmlToPDF(String htmlContent , Map<String,String> map ) throws Exception{
Document document = new Document();
//第二步,为该Document创建一个Writer实例:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document , byteArrayOutputStream);
//第三步,打开当前Document
document.open();
//第四步,为当前Document添加内容:
//替换内容
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new ByteArrayInputStream(htmlContent.getBytes("UTF-8")) ,
null , Charset.defaultCharset(),new FontProviderUtil());
//第五步,关闭Document
document.close();
byte[] buffer =byteArrayOutputStream.toByteArray();
InputStream sbs = new ByteArrayInputStream(buffer);
return getBase64FromInputStream(sbs);
}
public static String getBase64FromInputStream(InputStream in) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new String(Base64.encodeBase64(data));
}
public static void saveBase64strToFile(String base64str , String outPath){
if (base64str == null){
return ;
}
BASE64Decoder decoder = new BASE64Decoder();
try
{
byte[] b = decoder.decodeBuffer(base64str);
for(int i=0;i<b.length;++i)
{
if(b[i]<0){
b[i]+=256;
}
}
OutputStream out = new FileOutputStream(outPath);
out.write(b);
out.flush();
out.close();
}
catch (Exception e){
e.printStackTrace();
}
}
public static int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
}
package pps.core.common.pdf;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import sun.misc.BASE64Decoder;
import java.io.*;
public class UpdatePdfUtil {
/**
*
* @param bytes 数组
* @param contentText 添加的文字
* @return
* @throws Exception
*/
public static InputStream addText(byte[] bytes, String contentText)
throws Exception {
ByteArrayOutputStream byteArrayOutputStream = null;
PdfReader pdfReader = null;
PdfStamper stamper = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
pdfReader = new PdfReader(bytes);
Rectangle rectangle = pdfReader.getPageSize(1);
stamper = new PdfStamper(pdfReader, byteArrayOutputStream);
PdfContentByte canvas = stamper.getUnderContent(1);
//替换关键字
canvas.beginText();
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
canvas.setFontAndSize(bf, 13);
canvas.showTextAligned(Element.ALIGN_CENTER, contentText, rectangle.getWidth()-50, rectangle.getHeight()-20, 0);/*修正背景与文本的相对位置*/
canvas.endText();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
}
}
if (stamper != null)
try {
stamper.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (pdfReader != null) {
pdfReader.close();
}
}
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
}
public static void main(String[] args) throws Exception {
File pdfFile = new File("D:\\pdf\\test1664334027252.pdf");
//2.定义一个byte数组,长度为文件的长度
byte[] pdfData = new byte[(int) pdfFile.length()];
//3.IO流读取文件内容到byte数组
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(pdfFile);
inputStream.read(pdfData);
addText(pdfData,"dasfad");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
}
package pps.core.common.service;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.io.Files;
import org.apache.commons.lang3.StringUtils;
import pps.core.common.config.ObsConfig;
import pps.core.common.entity.SysFileAttachmentEnt;
import pps.core.common.enums.FileTypeEnum;
import pps.core.common.mapper.SysFileAttachmentMapper;
import pps.core.common.service.data.file.*;
import pps.core.common.service.data.sys_file_attachment.QuerySysFileAttachmentByIdsOutput;
import pps.core.common.session.PpsUserSession;
import pps.core.common.utils.HttpTookit;
import pps.core.common.utils.UUIDHelper;
import sun.misc.BASE64Decoder;
import xstartup.annotation.XService;
import xstartup.annotation.XText;
import xstartup.base.XContext;
import xstartup.base.XStartup;
import xstartup.base.pattern.XProviderManager;
import xstartup.base.tool.XStorageTool;
import xstartup.base.util.XFileUtils;
import xstartup.base.util.XUuidUtils;
import xstartup.config.XConfProperties;
import xstartup.config.XConfPropertiesHelper;
import xstartup.core.toolkit.provider.data.GetObjectUrlParam;
import xstartup.core.toolkit.provider.data.GetObjectUrlResult;
import xstartup.core.toolkit.provider.data.SaveObjectParam;
import xstartup.core.toolkit.provider.data.SaveObjectResult;
import xstartup.core.toolkit.provider.spec.XObjectStorageProvider;
import xstartup.data.XFileResult;
import xstartup.data.XFileType;
import xstartup.data.XServiceResult;
import xstartup.data.XSingleResult;
import xstartup.error.XError;
import xstartup.feature.api.annotation.XApiAnonymous;
import xstartup.feature.api.annotation.XApiGet;
import xstartup.feature.api.annotation.XApiPost;
import xstartup.feature.api.annotation.XApiUpload;
import xstartup.feature.mybatis.helper.XMapperHelper;
import xstartup.toolkit.office.helper.XExcelHelper;
import javax.activation.MimetypesFileTypeMap;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
@XService
public class FileService {
@XText("上传文件")
@XApiUpload
public XSingleResult<FileUploadOutput> uploadFile(XContext context, FileUploadInput input) throws IOException {
XConfProperties xConfProperties = XConfPropertiesHelper.find(context,
"x.storage",
"type",
new String[]{"endpoint", "access-key-id", "secret-access-key", "bucket-name", "region"},
XStartup.getCurrent().getName(),
true);
if (xConfProperties == null) {
return XSingleResult.error(XError.NotFound.getCode(), "配置信息没有找到");
}
XObjectStorageProvider provider = XProviderManager.findImplement(context,
XObjectStorageProvider.class,
xConfProperties.getProperty("type"));
if (provider == null) {
return XSingleResult.error(XError.NotFound.getCode(), "存储实现没有找到");
}
String contentType = new MimetypesFileTypeMap().getContentType(input.getFile().getFileName());
SaveObjectParam saveFileParam = new SaveObjectParam();
saveFileParam.setBucketName(xConfProperties.getProperty("bucket-name"));
saveFileParam.setAccessKeyId(xConfProperties.getProperty("access-key-id"));
saveFileParam.setSecretAccessKey(xConfProperties.getProperty("secret-access-key"));
saveFileParam.setEndpoint(xConfProperties.getProperty("endpoint", null));
saveFileParam.setRegion(xConfProperties.getProperty("region", null));
saveFileParam.setInputStream(input.getFile().getInputStream());
saveFileParam.setContentType(contentType);
saveFileParam.setFileName(input.getFile().getFileName());
saveFileParam.setFileKey(UUIDHelper.newUUID());
SaveObjectResult saveObjectResult = provider.saveObject(context, saveFileParam).orElseThrow();
SysFileAttachmentMapper mapper = context.getBean(SysFileAttachmentMapper.class);
SysFileAttachmentEnt entity = new SysFileAttachmentEnt();
PpsUserSession session = context.getSession(PpsUserSession.class);
entity.setBsnsId(input.getBsnsId());
entity.setFolderName(input.getFolderName());
entity.setFileKey(saveObjectResult.getFileKey());
entity.setAttachName(input.getFile().getFileName());
entity.setAttachSize(0);
entity.setAttachType(input.getFile().getExtension());
entity.setCreateById(session.getId());
entity.setCreateByName(session.getUserName());
entity.setCreateTime(new Date());
mapper.insert(entity);
FileUploadOutput uploadFileOutput = new FileUploadOutput();
uploadFileOutput.setFileKey(saveObjectResult.getFileKey());
return XSingleResult.success(uploadFileOutput);
}
@XText("上传base64")
@XApiPost
public XSingleResult<FileUploadOutput> uploadBase64(XContext context, Base64UploadInput input) throws IOException {
XConfProperties xConfProperties = XConfPropertiesHelper.find(context,
"x.storage",
"type",
new String[]{"endpoint", "access-key-id", "secret-access-key", "bucket-name", "region"},
XStartup.getCurrent().getName(),
true);
if (xConfProperties == null) {
return XSingleResult.error(XError.NotFound.getCode(), "配置信息没有找到");
}
XObjectStorageProvider provider = XProviderManager.findImplement(context,
XObjectStorageProvider.class,
xConfProperties.getProperty("type"));
if (provider == null) {
return XSingleResult.error(XError.NotFound.getCode(), "存储实现没有找到");
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes = decoder.decodeBuffer(input.getBase64Str());
InputStream inputStream = new ByteArrayInputStream(bytes);
String contentType = input.getSuffix();
if(!contentType.startsWith(".")){
contentType = "."+contentType;
}
FileTypeEnum byType = FileTypeEnum.findByType(contentType);
SaveObjectParam saveFileParam = new SaveObjectParam();
saveFileParam.setBucketName(xConfProperties.getProperty("bucket-name"));
saveFileParam.setAccessKeyId(xConfProperties.getProperty("access-key-id"));
saveFileParam.setSecretAccessKey(xConfProperties.getProperty("secret-access-key"));
saveFileParam.setEndpoint(xConfProperties.getProperty("endpoint", null));
saveFileParam.setRegion(xConfProperties.getProperty("region", null));
saveFileParam.setInputStream(inputStream);
saveFileParam.setContentType(byType.getFileType().getContentType());
saveFileParam.setFileName(input.getFileName());
saveFileParam.setFileKey(UUIDHelper.newUUID());
SaveObjectResult saveObjectResult = provider.saveObject(context, saveFileParam).orElseThrow();
SysFileAttachmentMapper mapper = context.getBean(SysFileAttachmentMapper.class);
SysFileAttachmentEnt entity = new SysFileAttachmentEnt();
PpsUserSession session = context.getSession(PpsUserSession.class);
entity.setBsnsId(input.getBsnsId());
entity.setFolderName(input.getFolderName());
entity.setFileKey(saveObjectResult.getFileKey());
entity.setAttachName(input.getFileName());
entity.setAttachSize(0);
entity.setAttachType(input.getSuffix());
entity.setCreateById(session.getId());
entity.setCreateByName(session.getUserName());
entity.setCreateTime(new Date());
mapper.insert(entity);
FileUploadOutput uploadFileOutput = new FileUploadOutput();
uploadFileOutput.setFileKey(saveObjectResult.getFileKey());
return XSingleResult.success(uploadFileOutput);
}
@XApiGet
@XText("获取文件地址")
public XSingleResult getDownloadUrl(XContext context, FileDownloadInput input){
XConfProperties xConfProperties = XConfPropertiesHelper.find(context,
"x.storage",
"type",
new String[]{"endpoint", "access-key-id", "secret-access-key", "bucket-name", "region"},
XStartup.getCurrent().getName(),
true);
context.getLogger().info("配置1信息xConfProperties:" + xConfProperties);
if (xConfProperties == null) {
return XSingleResult.error(XError.NotFound.getCode(), "配置信息没有找到");
}
XObjectStorageProvider provider = XProviderManager.findImplement(context,
XObjectStorageProvider.class,
xConfProperties.getProperty("type"));
if (provider == null) {
return XSingleResult.error(XError.NotFound.getCode(), "存储实现没有找到");
}
String fileKey = input.getFileKey();
GetObjectUrlParam getFileUrlParam = new GetObjectUrlParam();
getFileUrlParam.setEndpoint(xConfProperties.getProperty("endpoint", null));
getFileUrlParam.setRegion(xConfProperties.getProperty("region", null));
getFileUrlParam.setExpires(ObsConfig.urlExpires.getValue(context));
getFileUrlParam.setBucketName(xConfProperties.getProperty("bucket-name"));
getFileUrlParam.setFileKey(fileKey);
getFileUrlParam.setAccessKeyId(xConfProperties.getProperty("access-key-id"));
getFileUrlParam.setSecretAccessKey(xConfProperties.getProperty("secret-access-key"));
GetObjectUrlResult getFileUrlServiceResult = provider.getObjectUrl(context, getFileUrlParam).orElseThrow();
return XSingleResult.success(getFileUrlServiceResult.getUrl());
}
@XApiGet
@XText("下载文件")
public XFileResult downloadFile(XContext context, FileDownloadInput input){
//获取文件信息
SysFileAttachmentMapper mapper = context.getBean(SysFileAttachmentMapper.class);
QueryWrapper<SysFileAttachmentEnt> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().eq(SysFileAttachmentEnt::getFileKey,input.getFileKey());
SysFileAttachmentEnt sysFileAttachmentEnt = mapper.selectOne(queryWrapper);
if(sysFileAttachmentEnt==null){
return XFileResult.error(context, XError.NotFound);
}
String attachType = sysFileAttachmentEnt.getAttachType();
if(StringUtils.isBlank(attachType)){
return XFileResult.error(1000,"文件格式有误,请重新上传");
}
if(!attachType.startsWith(".")){
attachType = "."+attachType;
}
if(sysFileAttachmentEnt.getAttachName().endsWith(attachType)){
attachType = "";
}
String tempFile = XStorageTool.getAbsolutePath("/temp/file/" + sysFileAttachmentEnt.getAttachName() + attachType);
XSingleResult result = getDownloadUrl(context, input);
result.throwIfFail();
String downloadUrl = (String) result.getResult();
HttpsURLConnection connection = null;
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
URL url = new URL(downloadUrl);
HttpsURLConnection.setDefaultHostnameVerifier(HttpTookit.ignoreHostnameVerifier);
connection = (HttpsURLConnection) url.openConnection();
// Prepare SSL Context
TrustManager[] tm = { HttpTookit.ignoreCertificationTrustManger };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection.setSSLSocketFactory(ssf);
inputStream = connection.getInputStream();
byte[] buff = new byte[1024];
File file = new File(tempFile);
XFileUtils.deleteFile(file);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
outputStream = new FileOutputStream(file);
while (inputStream.read(buff) != -1) {
outputStream.write(buff, 0, buff.length);
outputStream.flush();
}
} catch (Exception e) {
context.getLogger().error("输出文件流失败:"+e.getMessage());
e.printStackTrace();
}finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != connection){
connection.disconnect();
}
context.getLogger().info("数据流处理完毕");
}
return XFileResult.success(FileTypeEnum.findByType(attachType).getFileType(), tempFile);
}
@XText("导入demo")
@XApiUpload
public XServiceResult importFile(XContext context, FileUploadInput input) {
InputStream inputStream = input.getFile().getInputStream();
//todo 解析文件,处理业务
return XServiceResult.OK;
}
@XText("导出demo")
@XApiGet(anonymous = true)
public XFileResult exportExcel(XContext context, ExportExcelInput input) {
String tempFile = XStorageTool.getAbsolutePath("/temp/excel/" + XUuidUtils.randomUUID() + ".xlsx");
List<ExcelModel> list = new ArrayList<>();
for(int index = 0; index < 10; index++){
ExcelModel excelModel = new ExcelModel();
excelModel.setText("测试"+index);
list.add(excelModel);
}
XExcelHelper.write(context, tempFile, "excel模版", list, ExcelModel.class);
return XFileResult.success(XFileType.APPLICATION_XLSX, tempFile);
}
/**
* url网络传输
* @param context
* @param fileKey
* @return
*/
public static XSingleResult getDownloadUrlByfileKey(XContext context, String fileKey){
XConfProperties xConfProperties = XConfPropertiesHelper.find(context,
"x.storage",
"type",
new String[]{"endpoint", "access-key-id", "secret-access-key", "bucket-name", "region"},
XStartup.getCurrent().getName(),
true);
context.getLogger().info("配置2信息xConfProperties:" + xConfProperties);
if (xConfProperties == null) {
return XSingleResult.error(XError.NotFound.getCode(), "配置信息没有找到");
}
XObjectStorageProvider provider = XProviderManager.findImplement(context,
XObjectStorageProvider.class,
xConfProperties.getProperty("type"));
if (provider == null) {
return XSingleResult.error(XError.NotFound.getCode(), "存储实现没有找到");
}
//String fileKey = input.getFileKey();
GetObjectUrlParam getFileUrlParam = new GetObjectUrlParam();
getFileUrlParam.setEndpoint(xConfProperties.getProperty("endpoint", null));
getFileUrlParam.setRegion(xConfProperties.getProperty("region", null));
getFileUrlParam.setExpires(ObsConfig.urlExpires.getValue(context));
getFileUrlParam.setBucketName(xConfProperties.getProperty("bucket-name"));
getFileUrlParam.setFileKey(fileKey);
getFileUrlParam.setAccessKeyId(xConfProperties.getProperty("access-key-id"));
getFileUrlParam.setSecretAccessKey(xConfProperties.getProperty("secret-access-key"));
GetObjectUrlResult getFileUrlServiceResult = provider.getObjectUrl(context, getFileUrlParam).orElseThrow();
return XSingleResult.success(getFileUrlServiceResult.getUrl());
}
@XText("批量下载")
@XApiGet
public XFileResult downloadFileZip(XContext context, FileBatchDownloadInput input) throws IOException {
if (CollectionUtil.isEmpty(input.getFileKeyList())) {
return XFileResult.error(1000,"需要压缩的附件fileKeyList不能为空");
}
SysFileAttachmentMapper mapper = context.getBean(SysFileAttachmentMapper.class);
QueryWrapper<SysFileAttachmentEnt> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().in(SysFileAttachmentEnt::getFileKey,input.getFileKeyList());
List<SysFileAttachmentEnt> ent_list = mapper.selectList(queryWrapper);
if (CollectionUtil.isEmpty(ent_list)) {
return XFileResult.error(context, XError.NotFound);
}
Set<String> set = new HashSet();
for (SysFileAttachmentEnt sysFileAttachmentEnt: ent_list) {
String attachType = sysFileAttachmentEnt.getAttachType();
if (StringUtils.isBlank(attachType)) {
context.getLogger().error("该文件格式有误:" + sysFileAttachmentEnt.getAttachName());
}
if (!attachType.startsWith(".")) {
attachType = "." + attachType;
}
if (sysFileAttachmentEnt.getAttachName().endsWith(attachType)) {
attachType = "";
}
//接收 obs取出附件后的 File路径
String tempFile = XStorageTool.getAbsolutePath("/temp/file/" + sysFileAttachmentEnt.getAttachName() + attachType);
context.getLogger().info("附件sysFileAttachmentEnt:" + sysFileAttachmentEnt.getFileKey());
FileDownloadInput fileDownloadInput = new FileDownloadInput();
fileDownloadInput.setFileKey(sysFileAttachmentEnt.getFileKey());
XSingleResult result = getDownloadUrl(context, fileDownloadInput);
result.throwIfFail();
String downloadUrl = (String) result.getResult();
HttpsURLConnection connection = null;
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
URL url = new URL(downloadUrl);
HttpsURLConnection.setDefaultHostnameVerifier(HttpTookit.ignoreHostnameVerifier);
connection = (HttpsURLConnection) url.openConnection();
TrustManager[] tm = { HttpTookit.ignoreCertificationTrustManger };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection.setSSLSocketFactory(ssf);
//通过obs的url网络传输 得到附件输入流
inputStream = connection.getInputStream();
byte[] buff = new byte[1024];
File file = new File(tempFile);
XFileUtils.deleteFile(file);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
outputStream = new FileOutputStream(file);
while (inputStream.read(buff) != -1) {
outputStream.write(buff, 0, buff.length);
outputStream.flush();
}
} catch (Exception e) {
context.getLogger().error("输出文件流失败:"+e.getMessage());
e.printStackTrace();
}finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != connection){
connection.disconnect();
}
context.getLogger().info("数据流处理完毕");
}
set.add(tempFile);
}
context.getLogger().info("附件set集合:" + set);
String tempUrl = System.getProperty("java.io.tmpdir") + "/temp/file/zip/";
String tempFilePath = tempUrl + encode(input.getFolderName()) + ".zip";
try {
int index = 0;
File[] srcFiles = new File[set.size()];
for (String path : set) {
srcFiles[index++] = new File(path);
}
context.getLogger().info("File数组:" + srcFiles);
//zip压缩
ZipUtil.zip(FileUtil.file(tempFilePath), true, srcFiles);
context.getLogger().info("zip压缩包的路径:" + tempFilePath);
} catch (Exception e) {
context.getLogger().error("zip压缩失败:" + e.getMessage());
}
return XFileResult.success(FileTypeEnum.findByType(".zip").getFileType(), tempFilePath);
}
/**
* 下载解决中文文件名乱码问题
*
* @param filename 文件名
* @return 编码后的文件名
* @throws UnsupportedEncodingException 编码错误
*/
private static String encode(String filename) throws UnsupportedEncodingException {
if (filename == null) {
return "null";
}
return URLEncoder.encode(Files.getNameWithoutExtension(filename), "UTF-8") + "." + Files.getFileExtension(filename);
}
}
......@@ -5,7 +5,7 @@
<parent>
<groupId>xstartup-cloud</groupId>
<artifactId>xstartup-cloud-parent-gateway</artifactId>
<version>1.15.169-xstartup-cloud</version>
<version>1.16.69-xstartup-v3-cloud</version>
<relativePath/>
</parent>
<modelVersion>4.0.0</modelVersion>
......@@ -14,9 +14,17 @@
<artifactId>deploy-pps-gateway</artifactId>
<dependencies>
<dependency>
<groupId>xstartup-cloud</groupId>
<artifactId>xstartup-cloud-feature-huawei-cse-gateway</artifactId>
<artifactId>xstartup-cloud-feature-alibaba</artifactId>
<version>1.16.69-xstartup-v3-cloud</version>
</dependency>
<dependency>
<groupId>xstartup</groupId>
<artifactId>xstartup-feature-cors</artifactId>
<version>1.16.69-xstartup-v3</version>
<scope>compile</scope>
</dependency>
</dependencies>
<profiles>
......
......@@ -3,7 +3,7 @@ package app;
import xstartup.base.XStartup;
import xstartup.base.conf.XServerConf;
import xstartup.boot.XStartupApplication;
import xstartup.feature.cloud.XCloudHuaweiCseGatewayFeature;
import xstartup.feature.cloud.XCloudAlibabaFeature;
/**
* 网关模块启动程序
......@@ -15,7 +15,7 @@ public class DeployPpsGatewayApplication {
public static void main(String... args) {
XStartup startup = new XStartupApplication("pps");
startup.config(new XServerConf(22068).naming("pps-gateway"));
startup.enable(XCloudHuaweiCseGatewayFeature.class);
startup.enable(XCloudAlibabaFeature.class);
startup.run(args);
}
}
......@@ -20,11 +20,18 @@ x.db.password=@x.db.password@
x.db.naming=@x.db.naming@
#cors
x.cors.origin-pattern=*
#\u6CE8\u518C\u4E2D\u5FC3\u5730\u5740
x.cloud.discovery.server-addr=@spring.cloud.servicecomb.discovery.address@
#\u6CE8\u518C\u7684\u5E94\u7528\u540D\u79F0\uFF08\u975E\u5FAE\u670D\u52A1\u540D\u79F0\uFF0C\u5FAE\u670D\u52A1\u540D\u79F0\u5728\u4EE3\u7801\u91CC\u8BBE\u7F6E\u4E86\uFF09
x.cloud.discovery.app-name=pps-application
#\u7528\u6237\u540D
x.cloud.discovery.username=@spring.cloud.servicecomb.credentials.account.name@
#\u5BC6\u7801
x.cloud.discovery.password=@spring.cloud.servicecomb.credentials.account.password@
\ No newline at end of file
x.cors.exposed-headers=*
spring.autoconfigure.exclude=*
#\u6CE8\u518C\u4E2D\u5FC3
x.cloud.discovery.server-addr=@x.cloud.discovery.server-addr@
x.cloud.discovery.namespace=@x.cloud.discovery.namespace@
x.cloud.discovery.group=@x.cloud.discovery.group@
x.cloud.discovery.username=@x.cloud.discovery.username@
x.cloud.discovery.password=@x.cloud.discovery.password@
#\u914D\u7F6E\u4E2D\u5FC3
x.cloud.config.server-addr=@x.cloud.config.server-addr@
x.cloud.config.namespace=@x.cloud.config.namespace@
x.cloud.config.group=@x.cloud.config.group@
x.cloud.config.file-extension=@x.cloud.config.file-extension@
x.cloud.config.username=@x.cloud.config.username@
x.cloud.config.password=@x.cloud.config.password@
\ No newline at end of file
......@@ -5,7 +5,7 @@
<parent>
<groupId>xstartup-cloud</groupId>
<artifactId>xstartup-cloud-parent-app</artifactId>
<version>1.15.169-xstartup-cloud</version>
<version>1.16.69-xstartup-v3-cloud</version>
<relativePath/>
</parent>
<modelVersion>4.0.0</modelVersion>
......@@ -29,10 +29,6 @@
<groupId>xstartup</groupId>
<artifactId>xstartup-feature-mybatis</artifactId>
</dependency>
<dependency>
<groupId>xstartup-cloud</groupId>
<artifactId>xstartup-cloud-feature-huawei-cse</artifactId>
</dependency>
<dependency>
<groupId>xstartup</groupId>
<artifactId>xstartup-feature-swagger-doc</artifactId>
......@@ -42,6 +38,11 @@
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>xstartup-cloud</groupId>
<artifactId>xstartup-cloud-feature-alibaba</artifactId>
<version>1.16.69-xstartup-v3-cloud</version>
</dependency>
</dependencies>
<profiles>
......
......@@ -9,7 +9,7 @@ import xstartup.boot.XStartupApplication;
import xstartup.feature.XSwaggerDocFeature;
import xstartup.feature.api.XApiFeature;
import xstartup.feature.api.conf.XApiCookieConf;
import xstartup.feature.cloud.XCloudHuaweiCseFeature;
import xstartup.feature.cloud.XCloudAlibabaFeature;
import xstartup.feature.mybatis.XMybatisFeature;
import xstartup.feature.rpc.XRpcFeature;
......@@ -27,7 +27,7 @@ public class DeployPpsSystemApplication {
.config(new XServiceConf("pps"));
startup.enable(XApiFeature.class)
.config(new XApiCookieConf("%4bH8s9&", 43200));
startup.enable(XCloudHuaweiCseFeature.class);
startup.enable(XCloudAlibabaFeature.class);
startup.enable(XSwaggerDocFeature.class);
startup.enable(XMybatisFeature.class);
startup.enable(XRpcFeature.class);
......
......@@ -33,11 +33,16 @@ x.db.pps.core.system.user=@x.db.pps.core.system.user@
x.db.pps.core.system.password=@x.db.pps.core.system.password@
x.db.pps.core.system.naming=@x.db.pps.core.system.naming@
pps.core.common.trace-log-config.enabletracelog=true
#\u6CE8\u518C\u4E2D\u5FC3\u5730\u5740
x.cloud.discovery.server-addr=@spring.cloud.servicecomb.discovery.address@
#\u6CE8\u518C\u7684\u5E94\u7528\u540D\u79F0\uFF08\u975E\u5FAE\u670D\u52A1\u540D\u79F0\uFF0C\u5FAE\u670D\u52A1\u540D\u79F0\u5728\u4EE3\u7801\u91CC\u8BBE\u7F6E\u4E86\uFF09
x.cloud.discovery.app-name=pps-application
#\u7528\u6237\u540D
x.cloud.discovery.username=@spring.cloud.servicecomb.credentials.account.name@
#\u5BC6\u7801
x.cloud.discovery.password=@spring.cloud.servicecomb.credentials.account.password@
#\u6CE8\u518C\u4E2D\u5FC3
x.cloud.discovery.server-addr=@x.cloud.discovery.server-addr@
x.cloud.discovery.namespace=@x.cloud.discovery.namespace@
x.cloud.discovery.group=@x.cloud.discovery.group@
x.cloud.discovery.username=@x.cloud.discovery.username@
x.cloud.discovery.password=@x.cloud.discovery.password@
#\u914D\u7F6E\u4E2D\u5FC3
x.cloud.config.server-addr=@x.cloud.config.server-addr@
x.cloud.config.namespace=@x.cloud.config.namespace@
x.cloud.config.group=@x.cloud.config.group@
x.cloud.config.file-extension=@x.cloud.config.file-extension@
x.cloud.config.username=@x.cloud.config.username@
x.cloud.config.password=@x.cloud.config.password@
......@@ -74,13 +74,20 @@ x.db.pps.core.system.user=root
x.db.pps.core.system.password=vwy69PQDfShqozf4ISXEoQ==
x.db.pps.core.system.naming=snake-case
#huawei-cse config \u4E50\u5F3A\uFF1A10.12.1.98 \u5B66\u71D5\uFF1A10.12.4.102 10.12.0.205 \u5218\u5F3A:10.12.6.213\u4E13\u7EBFcse\u5730\u5740:11.0.25.197
spring.cloud.servicecomb.discovery.address=http://127.0.0.1:30100
spring.cloud.servicecomb.config.serverType=kie
spring.cloud.servicecomb.config.serverAddr=http://127.0.0.1:30110
spring.cloud.servicecomb.credentials.account.name=
spring.cloud.servicecomb.credentials.account.password=
spring.cloud.servicecomb.credentials.account.cipher=
#nacos-\u6CE8\u518C\u4E2D\u5FC3
x.cloud.discovery.server-addr=192.168.0.128:8848
x.cloud.discovery.namespace=public
x.cloud.discovery.group=DEFAULT_GROUP
x.cloud.discovery.username=nacos
x.cloud.discovery.password=nacos
#nacos-\u914D\u7F6E\u4E2D\u5FC3
x.cloud.config.server-addr=192.168.0.128:8848
x.cloud.config.namespace=piublic
x.cloud.config.group=DEFAULT_GROUP
x.cloud.config.file-extension=properties
x.cloud.config.username=nacos
x.cloud.config.password=nacos
# \u81EA\u5B9A\u4E49\u914D\u7F6E
#weather.file.temp.path=D:/home/weather/temp/receive
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment