Commit 7b6015f9 authored by zhangsen's avatar zhangsen

漏洞文件漏洞修改 - 流未关闭问题

parent c2a90a0a
...@@ -28,11 +28,9 @@ import org.slf4j.Logger; ...@@ -28,11 +28,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import java.io.BufferedReader; import java.io.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
...@@ -407,31 +405,33 @@ public class HttpContentTypeUtil { ...@@ -407,31 +405,33 @@ public class HttpContentTypeUtil {
/** /**
* 发送 delete请求带请求头 * 发送 delete请求带请求头
*/ */
public static String sendHttpDeleteJsonWithHeader(String httpUrl, String paramsJson, Map<String, String> headerMap) { public static String sendHttpDeleteJsonWithHeader(String httpUrl, String paramsJson, Map<String, String> headerMap) throws IOException {
StringBuffer content = new StringBuffer(); StringBuffer content = new StringBuffer();
try { URL url = new URL(httpUrl);
URL url = new URL(httpUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("DELETE");
connection.setRequestMethod("DELETE"); connection.setDoInput(true);
connection.setDoInput(true); connection.setDoOutput(true);
connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); for (Map.Entry<String, String> entry : headerMap.entrySet()) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue());
connection.setRequestProperty(entry.getKey(), entry.getValue()); }
} try (
PrintWriter printWriter = new PrintWriter(connection.getOutputStream()); PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(inputStreamReader);
) {
printWriter.write(paramsJson); printWriter.write(paramsJson);
printWriter.flush(); printWriter.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
content.append(line); content.append(line);
} }
br.close();
connection.disconnect(); connection.disconnect();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
} }
return content.toString(); return content.toString();
} }
......
...@@ -41,19 +41,13 @@ public class MyImageExtractor implements IImageExtractor { ...@@ -41,19 +41,13 @@ public class MyImageExtractor implements IImageExtractor {
imagePath = s1 + pre + s2; imagePath = s1 + pre + s2;
File imageFile = new File(baseDir, imagePath); File imageFile = new File(baseDir, imagePath);
imageFile.getParentFile().mkdirs(); imageFile.getParentFile().mkdirs();
InputStream in = null; try (
OutputStream out = null; InputStream in = new ByteArrayInputStream(imageData);
try { OutputStream out = new FileOutputStream(imageFile);
in = new ByteArrayInputStream(imageData); ) {
out = new FileOutputStream(imageFile);
IOUtils.copy(in, out); IOUtils.copy(in, out);
} finally { } catch (IOException e) {
if (in != null) { e.printStackTrace();
IOUtils.closeQuietly(in);
}
if (out != null) {
IOUtils.closeQuietly(out);
}
} }
} }
......
...@@ -67,9 +67,8 @@ public class TikaUtils { ...@@ -67,9 +67,8 @@ public class TikaUtils {
ContentHandler handler = new ToHTMLContentHandler(); ContentHandler handler = new ToHTMLContentHandler();
AutoDetectParser parser = new AutoDetectParser(); AutoDetectParser parser = new AutoDetectParser();
Metadata metadata = new Metadata(); Metadata metadata = new Metadata();
InputStream stream = null; try (InputStream stream = new FileInputStream(new File(fileName));) {
try {
stream = new FileInputStream(new File(fileName));
parser.parse(stream, handler, metadata); parser.parse(stream, handler, metadata);
FileHelper.writeFile(handler.toString(), outPutFile + ".html"); FileHelper.writeFile(handler.toString(), outPutFile + ".html");
...@@ -78,8 +77,6 @@ public class TikaUtils { ...@@ -78,8 +77,6 @@ public class TikaUtils {
return null; return null;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
} }
return ""; return "";
......
...@@ -78,7 +78,10 @@ public class WordConverterUtils { ...@@ -78,7 +78,10 @@ public class WordConverterUtils {
* @param readUrl html中img标签的图片存储路径 * @param readUrl html中img标签的图片存储路径
*/ */
private static void docToHtml(File srcFile, File targetFile, String readUrl) { private static void docToHtml(File srcFile, File targetFile, String readUrl) {
try { try (
FileInputStream inputStream = new FileInputStream(srcFile);
HWPFDocument wordDocument = new HWPFDocument(inputStream);
) {
String imagePathStr = srcFile.getParentFile().getAbsolutePath() + imgPath; String imagePathStr = srcFile.getParentFile().getAbsolutePath() + imgPath;
File imagePath = new File(imagePathStr); File imagePath = new File(imagePathStr);
if (!imagePath.exists()) { if (!imagePath.exists()) {
...@@ -86,13 +89,12 @@ public class WordConverterUtils { ...@@ -86,13 +89,12 @@ public class WordConverterUtils {
} }
String srcName = srcFile.getName(); String srcName = srcFile.getName();
String suffix = srcName.substring(0, srcName.lastIndexOf(".")) + "_"; String suffix = srcName.substring(0, srcName.lastIndexOf(".")) + "_";
HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(srcFile));
org.w3c.dom.Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); org.w3c.dom.Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document); WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);
String uri = readUrl + imagePathStr.substring(imagePathStr.indexOf("docs")); String uri = readUrl + imagePathStr.substring(imagePathStr.indexOf("docs"));
wordToHtmlConverter.setPicturesManager((content, pictureType, name, width, height) -> { wordToHtmlConverter.setPicturesManager((content, pictureType, name, width, height) -> {
try { try (FileOutputStream out = new FileOutputStream(imagePathStr + suffix + name);) {
FileOutputStream out = new FileOutputStream(imagePathStr + suffix + name);
out.write(content); out.write(content);
return uri + suffix + name; return uri + suffix + name;
} catch (Exception e) { } catch (Exception e) {
...@@ -124,7 +126,10 @@ public class WordConverterUtils { ...@@ -124,7 +126,10 @@ public class WordConverterUtils {
* @return * @return
*/ */
private static String docToHtmlString(File srcFile, String readUrl) { private static String docToHtmlString(File srcFile, String readUrl) {
try { try (
FileInputStream inputStream = new FileInputStream(srcFile);
HWPFDocument wordDocument = new HWPFDocument(inputStream);
) {
String imagePathStr = srcFile.getParentFile().getAbsolutePath() + imgPath; String imagePathStr = srcFile.getParentFile().getAbsolutePath() + imgPath;
File imagePath = new File(imagePathStr); File imagePath = new File(imagePathStr);
if (!imagePath.exists()) { if (!imagePath.exists()) {
...@@ -132,13 +137,12 @@ public class WordConverterUtils { ...@@ -132,13 +137,12 @@ public class WordConverterUtils {
} }
String srcName = srcFile.getName(); String srcName = srcFile.getName();
String suffix = srcName.substring(0, srcName.lastIndexOf(".")) + "_"; String suffix = srcName.substring(0, srcName.lastIndexOf(".")) + "_";
HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(srcFile));
org.w3c.dom.Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); org.w3c.dom.Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document); WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);
String uri = readUrl + imagePathStr.substring(imagePathStr.indexOf("docs")); String uri = readUrl + imagePathStr.substring(imagePathStr.indexOf("docs"));
wordToHtmlConverter.setPicturesManager((content, pictureType, name, width, height) -> { wordToHtmlConverter.setPicturesManager((content, pictureType, name, width, height) -> {
try { try (FileOutputStream out = new FileOutputStream(imagePathStr + suffix + name);) {
FileOutputStream out = new FileOutputStream(imagePathStr + suffix + name);
out.write(content); out.write(content);
return uri + suffix + name; return uri + suffix + name;
} catch (Exception e) { } catch (Exception e) {
...@@ -183,30 +187,22 @@ public class WordConverterUtils { ...@@ -183,30 +187,22 @@ public class WordConverterUtils {
} }
String temp = srcFile.getName(); String temp = srcFile.getName();
String suffix = temp.substring(0, temp.lastIndexOf(".")) + "_"; String suffix = temp.substring(0, temp.lastIndexOf(".")) + "_";
OutputStreamWriter outputStreamWriter = null; try (
try { FileInputStream inputStream = new FileInputStream(srcFile);
XWPFDocument document = new XWPFDocument(new FileInputStream(srcFile)); XWPFDocument document = new XWPFDocument(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "utf-8");
) {
XHTMLOptions options = XHTMLOptions.create(); XHTMLOptions options = XHTMLOptions.create();
options.setExtractor(new MyImageExtractor(imagePath, suffix)); options.setExtractor(new MyImageExtractor(imagePath, suffix));
String uri = readUrl + imagePathStr.substring(imagePathStr.indexOf("docs")); String uri = readUrl + imagePathStr.substring(imagePathStr.indexOf("docs"));
System.out.println("uri :" + uri); System.out.println("uri :" + uri);
options.URIResolver(new MyURIResolver(uri)); options.URIResolver(new MyURIResolver(uri));
outputStreamWriter = new OutputStreamWriter(new FileOutputStream(targetFile), "utf-8");
XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance(); XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
xhtmlConverter.convert(document, outputStreamWriter, options); xhtmlConverter.convert(document, outputStreamWriter, options);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
} }
} }
/** /**
...@@ -223,9 +219,11 @@ public class WordConverterUtils { ...@@ -223,9 +219,11 @@ public class WordConverterUtils {
} }
String temp = srcFile.getName(); String temp = srcFile.getName();
String suffix = temp.substring(0, temp.lastIndexOf(".")) + "_"; String suffix = temp.substring(0, temp.lastIndexOf(".")) + "_";
OutputStreamWriter outputStreamWriter = null; try (
try { FileInputStream inputStream = new FileInputStream(srcFile);
XWPFDocument document = new XWPFDocument(new FileInputStream(srcFile)); XWPFDocument document = new XWPFDocument(inputStream);
) {
XHTMLOptions options = XHTMLOptions.create(); XHTMLOptions options = XHTMLOptions.create();
options.setExtractor(new MyImageExtractor(imagePath, suffix)); options.setExtractor(new MyImageExtractor(imagePath, suffix));
String uri = readUrl + imagePathStr.substring(imagePathStr.indexOf("docs")); String uri = readUrl + imagePathStr.substring(imagePathStr.indexOf("docs"));
...@@ -237,15 +235,6 @@ public class WordConverterUtils { ...@@ -237,15 +235,6 @@ public class WordConverterUtils {
return stringWriter.toString(); return stringWriter.toString();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
} }
return null; return null;
......
...@@ -82,8 +82,7 @@ public class WordHtml implements AbstractHtml { ...@@ -82,8 +82,7 @@ public class WordHtml implements AbstractHtml {
private static void convertDoc2Html(InputStream is, String outPutFile) private static void convertDoc2Html(InputStream is, String outPutFile)
throws TransformerException, IOException, ParserConfigurationException { throws TransformerException, IOException, ParserConfigurationException {
StreamResult streamResult = null; StreamResult streamResult = null;
ByteArrayOutputStream out = null; try (ByteArrayOutputStream out = new ByteArrayOutputStream();) {
try {
String[] outPutFiles = outPutFile.split("\\\\"); String[] outPutFiles = outPutFile.split("\\\\");
outPutFiles = outPutFiles[outPutFiles.length - 1].split("/"); outPutFiles = outPutFiles[outPutFiles.length - 1].split("/");
final String root = outPutFiles[outPutFiles.length - 1]; final String root = outPutFiles[outPutFiles.length - 1];
...@@ -106,17 +105,16 @@ public class WordHtml implements AbstractHtml { ...@@ -106,17 +105,16 @@ public class WordHtml implements AbstractHtml {
if (pics != null) { if (pics != null) {
for (int i = 0; i < pics.size(); i++) { for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i); Picture pic = (Picture) pics.get(i);
try { try (FileOutputStream fileOutputStream = new FileOutputStream(outPutFile + "/" + pic.suggestFullFileName());) {
// 指定doc文档中转换后图片保存的路径 // 指定doc文档中转换后图片保存的路径
pic.writeImageContent( pic.writeImageContent(fileOutputStream);
new FileOutputStream(outPutFile + "/" + pic.suggestFullFileName()));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
// #end save pictures // #end save pictures
out = new ByteArrayOutputStream();
streamResult = new StreamResult(out); streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance(); TransformerFactory tf = TransformerFactory.newInstance();
...@@ -134,10 +132,8 @@ public class WordHtml implements AbstractHtml { ...@@ -134,10 +132,8 @@ public class WordHtml implements AbstractHtml {
FileHelper.writeFile(content, outPutFile + ".html"); FileHelper.writeFile(content, outPutFile + ".html");
// FileHelper.parseCharset(outPutFile + ".html"); // FileHelper.parseCharset(outPutFile + ".html");
// System.out.println(new String(out.toByteArray())); // System.out.println(new String(out.toByteArray()));
} finally { } catch (IOException e) {
if (null != out) { e.printStackTrace();
out.close();
}
} }
} }
...@@ -195,45 +191,29 @@ public class WordHtml implements AbstractHtml { ...@@ -195,45 +191,29 @@ public class WordHtml implements AbstractHtml {
} }
public static void xml2Ttml(String docPath, String xsltPath, String hrmlPath){ public static void xml2Ttml(String docPath, String xsltPath, String hrmlPath) {
FileInputStream fis= null;
FileInputStream fis1= null; try (
try { //创建XML的文件输入流
//创建XML的文件输入流 FileInputStream fis = new FileInputStream(docPath);
fis = new FileInputStream(docPath); //创建XSL文件的输入流
Source source=new StreamSource(fis); FileInputStream fis1 = new FileInputStream(xsltPath);
PrintStream stm = new PrintStream(new File(hrmlPath));
//创建XSL文件的输入流 ) {
fis1 = new FileInputStream(xsltPath);
Source template=new StreamSource(fis1); Source source = new StreamSource(fis);
Source template = new StreamSource(fis1);
PrintStream stm=new PrintStream(new File(hrmlPath)); //讲转换后的结果输出到 stm 中即 F:\123.html
//讲转换后的结果输出到 stm 中即 F:\123.html Result result = new StreamResult(stm);
Result result=new StreamResult(stm); //根据XSL文件创建准个转换对象
//根据XSL文件创建准个转换对象 TransformerFactory transformerFactory = TransformerFactory.newInstance();
TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = transformerFactory.newTransformer(template);
Transformer transformer=transformerFactory.newTransformer(template); //处理xml进行交换
//处理xml进行交换 transformer.transform(source, result);
transformer.transform(source, result); } catch (IOException | TransformerException e) {
} catch (FileNotFoundException e) { e.printStackTrace();
e.printStackTrace(); }
} catch (TransformerException e) {
e.printStackTrace();
} finally {
//关闭文件流
try {
if(null != fis1){
fis1.close();
}
if(null != fis){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} }
} }
......
...@@ -89,27 +89,16 @@ public class WordTemplateUtils { ...@@ -89,27 +89,16 @@ public class WordTemplateUtils {
public File getWordFileItem(Map map, String title, String ftlFile) throws IOException { public File getWordFileItem(Map map, String title, String ftlFile) throws IOException {
configuration.setClassForTemplateLoading(this.getClass(), "/ftl"); configuration.setClassForTemplateLoading(this.getClass(), "/ftl");
Template freemarkerTemplate = configuration.getTemplate(ftlFile, "UTF-8"); Template freemarkerTemplate = configuration.getTemplate(ftlFile, "UTF-8");
File file = null; // 调用工具类的createDoc方法生成Word文档
File file = createDoc(map, freemarkerTemplate);
File filepdf = new File("sellPlan.pdf"); File filepdf = new File("sellPlan.pdf");
InputStream fin = null; try (
OutputStream os = null; InputStream fin =new FileInputStream(file) ;
try { OutputStream os = new FileOutputStream(filepdf);
// 调用工具类的createDoc方法生成Word文档 )
file = createDoc(map, freemarkerTemplate); {
fin = new FileInputStream(file);
os = new FileOutputStream(filepdf);
wordTopdfByAspose(fin, os); wordTopdfByAspose(fin, os);
return filepdf; return filepdf;
} finally {
if (fin != null) {
fin.close();
}
if (os != null) {
os.close();
}
if (file != null) {
file.delete();
}// 删除临时文件
} }
} }
......
...@@ -51,17 +51,25 @@ public class IOConfig { ...@@ -51,17 +51,25 @@ public class IOConfig {
tmp2.put("lower-greek", 1L); tmp2.put("lower-greek", 1L);
ILV1_MAP = Collections.unmodifiableMap(tmp2); ILV1_MAP = Collections.unmodifiableMap(tmp2);
NumberingDefinitionsPart numberingDefinitionsPart = null; NumberingDefinitionsPart numberingDefinitionsPart = null;
try { try (
numberingDefinitionsPart = new NumberingDefinitionsPart(); InputStream is = IOConfig.class.getClassLoader().getResourceAsStream("office/listStyle.xml");
InputStream is = IOConfig.class.getClassLoader().getResourceAsStream("office/listStyle.xml"); ) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); assert is != null;
StringBuilder builder = new StringBuilder(); try (InputStreamReader inputStreamReader = new InputStreamReader(is, "UTF-8");
String str; BufferedReader reader = new BufferedReader(inputStreamReader);
while ((str = reader.readLine()) != null) { ) {
builder.append(str); numberingDefinitionsPart = new NumberingDefinitionsPart();
StringBuilder builder = new StringBuilder();
String str;
while ((str = reader.readLine()) != null) {
builder.append(str);
}
Numbering numbering = (Numbering) XmlUtils.unmarshalString(builder.toString());
numberingDefinitionsPart.setJaxbElement(numbering);
} catch (Exception e) {
e.printStackTrace();
} }
Numbering numbering = (Numbering) XmlUtils.unmarshalString(builder.toString());
numberingDefinitionsPart.setJaxbElement(numbering);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -495,6 +495,7 @@ public class DocxBuilder { ...@@ -495,6 +495,7 @@ public class DocxBuilder {
*/ */
private static byte[] getRemotePic2Bytes(String picUrl) { private static byte[] getRemotePic2Bytes(String picUrl) {
byte[] picBytes = {}; byte[] picBytes = {};
InputStream is = null;
try { try {
if (picUrl.startsWith(IOConfig.PIC_ROUTER)) { if (picUrl.startsWith(IOConfig.PIC_ROUTER)) {
picUrl = picUrl.replaceFirst(IOConfig.PIC_ROUTER, IOConfig.PIC_URI); picUrl = picUrl.replaceFirst(IOConfig.PIC_ROUTER, IOConfig.PIC_URI);
...@@ -504,7 +505,7 @@ public class DocxBuilder { ...@@ -504,7 +505,7 @@ public class DocxBuilder {
// 设置请求超时为5s // 设置请求超时为5s
con.setConnectTimeout(5 * 1000); con.setConnectTimeout(5 * 1000);
// 输入流 // 输入流
InputStream is = con.getInputStream(); is = con.getInputStream();
// 1K的数据缓冲 // 1K的数据缓冲
byte[] current = new byte[1024]; byte[] current = new byte[1024];
// 读取到的数据长度 // 读取到的数据长度
...@@ -513,9 +514,16 @@ public class DocxBuilder { ...@@ -513,9 +514,16 @@ public class DocxBuilder {
picBytes = Arrays.copyOf(picBytes, picBytes.length + len); picBytes = Arrays.copyOf(picBytes, picBytes.length + len);
System.arraycopy(current, 0, picBytes, picBytes.length - len, len); System.arraycopy(current, 0, picBytes, picBytes.length - len, len);
} }
is.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
return picBytes; return picBytes;
} }
......
...@@ -272,17 +272,14 @@ public class EquipmentManageServiceImpl extends ServiceImpl<EquipmentManageMappe ...@@ -272,17 +272,14 @@ public class EquipmentManageServiceImpl extends ServiceImpl<EquipmentManageMappe
@Override @Override
public void downLoad(FileUploadVo vo, HttpServletResponse response) { public void downLoad(FileUploadVo vo, HttpServletResponse response) {
String fileName = vo.getName() ; String fileName = vo.getName() ;
ServletOutputStream out;
response.setHeader("Content-Disposition", "attachment;fileName="+fileName); response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
response.setHeader("Access-Control-Expose-Headers", "access_token"); response.setHeader("Access-Control-Expose-Headers", "access_token");
response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("multipart/form-data"); response.setContentType("multipart/form-data");
try { try (InputStream inputStream = getInputStreamFromURL(vo.getUrl());
InputStream inputStream = getInputStreamFromURL(vo.getUrl()); //3.通过response获取ServletOutputStream对象(out)
ServletOutputStream out = response.getOutputStream();
//3.通过response获取ServletOutputStream对象(out) ) {
out = response.getOutputStream();
int b = 0; int b = 0;
byte[] buffer = new byte[512]; byte[] buffer = new byte[512];
while (b != -1){ while (b != -1){
...@@ -290,10 +287,7 @@ public class EquipmentManageServiceImpl extends ServiceImpl<EquipmentManageMappe ...@@ -290,10 +287,7 @@ public class EquipmentManageServiceImpl extends ServiceImpl<EquipmentManageMappe
//4.写到输出流(out)中 //4.写到输出流(out)中
out.write(buffer,0,b); out.write(buffer,0,b);
} }
inputStream.close();
out.close();
out.flush(); out.flush();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -41,7 +41,9 @@ public class ExcelUtil { ...@@ -41,7 +41,9 @@ public class ExcelUtil {
Class<?> model, String token, String appKey, String product, boolean flag) { Class<?> model, String token, String appKey, String product, boolean flag) {
HorizontalCellStyleStrategy horizontalCellStyleStrategy = setMyCellStyle(); HorizontalCellStyleStrategy horizontalCellStyleStrategy = setMyCellStyle();
try { try (
OutputStream outputStream = getOutputStream(fileName, response, ExcelTypeEnum.XLSX);
) {
//下拉列表集合 //下拉列表集合
Map<Integer, String[]> explicitListConstraintMap = new HashMap<>(); Map<Integer, String[]> explicitListConstraintMap = new HashMap<>();
if (flag) { if (flag) {
...@@ -54,7 +56,7 @@ public class ExcelUtil { ...@@ -54,7 +56,7 @@ public class ExcelUtil {
resolveExplicitConstraint(explicitListConstraintMap, explicitConstraint,token,appKey,product); resolveExplicitConstraint(explicitListConstraintMap, explicitConstraint,token,appKey,product);
} }
} }
EasyExcel.write(getOutputStream(fileName, response, ExcelTypeEnum.XLSX), model) EasyExcel.write(outputStream, model)
.excelType(ExcelTypeEnum.XLSX).sheet(sheetName) .excelType(ExcelTypeEnum.XLSX).sheet(sheetName)
.registerWriteHandler(new TemplateCellWriteHandlerDate(explicitListConstraintMap)) .registerWriteHandler(new TemplateCellWriteHandlerDate(explicitListConstraintMap))
.registerWriteHandler(new TemplateCellWriteHandler()) .registerWriteHandler(new TemplateCellWriteHandler())
......
...@@ -434,62 +434,50 @@ public class FileHelper { ...@@ -434,62 +434,50 @@ public class FileHelper {
} }
public static void nioTransferCopy(File source, File target) { public static void nioTransferCopy(File source, File target) {
FileChannel in = null; try (
FileChannel out = null; FileInputStream inStream = new FileInputStream(source);
FileInputStream inStream = null; FileOutputStream outStream = new FileOutputStream(target);
FileOutputStream outStream = null; FileChannel in = inStream.getChannel();
try { FileChannel out = outStream.getChannel();
inStream = new FileInputStream(source); ) {
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
in.transferTo(0, in.size(), out); in.transferTo(0, in.size(), out);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
} }
} }
private static boolean nioBufferCopy(File source, File target) { private static boolean nioBufferCopy(File source, File target) {
FileChannel in = null;
FileChannel out = null; try (
FileInputStream inStream = null; FileInputStream inStream = new FileInputStream(source);
FileOutputStream outStream = null; FileOutputStream outStream = new FileOutputStream(target);
try { FileChannel in = inStream.getChannel();
inStream = new FileInputStream(source); FileChannel out = outStream.getChannel();
outStream = new FileOutputStream(target); ) {
in = inStream.getChannel();
out = outStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4096); ByteBuffer buffer = ByteBuffer.allocate(4096);
while (in.read(buffer) != -1) { while (in.read(buffer) != -1) {
buffer.flip(); buffer.flip();
out.write(buffer); out.write(buffer);
buffer.clear(); buffer.clear();
} }
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
} }
return true; return true;
} }
public static void customBufferStreamCopy(File source, File target) { public static void customBufferStreamCopy(File source, File target) {
InputStream fis = null; try (
OutputStream fos = null; InputStream fis = new FileInputStream(source);
try { OutputStream fos = new FileOutputStream(target);
fis = new FileInputStream(source); ) {
fos = new FileOutputStream(target);
byte[] buf = new byte[4096]; byte[] buf = new byte[4096];
int i; int i;
while ((i = fis.read(buf)) != -1) { while ((i = fis.read(buf)) != -1) {
...@@ -497,9 +485,6 @@ public class FileHelper { ...@@ -497,9 +485,6 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
close(fis);
close(fos);
} }
} }
......
...@@ -851,35 +851,33 @@ public class CheckController extends AbstractBaseController { ...@@ -851,35 +851,33 @@ public class CheckController extends AbstractBaseController {
} }
InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
Source source = new StreamSource(inputStream); Source source = new StreamSource(inputStream);
try { String filePath = Objects.requireNonNull(this.getClass().getResource("/")).getPath() + "temp" + File.separator + "checkTemplate.xsl";
String filePath = Objects.requireNonNull(this.getClass().getResource("/")).getPath() + "temp" + File.separator + "checkTemplate.xsl"; if (Files.notExists(Paths.get(filePath))) {
if (Files.notExists(Paths.get(filePath))) { throw new RuntimeException("模板文件不存在");
throw new RuntimeException("模板文件不存在"); }
}
FileInputStream fis1 = new FileInputStream(FilenameUtils.normalize(filePath)); Date date = new Date();
String path = request.getSession().getServletContext().getRealPath("/");
String subPath = path.substring(0, path.indexOf(File.separator) + 1);
String dir = subPath + "check";
String html = subPath + "check" + File.separator + "task_"
+ date.getTime() + ".html";
File htmlFile = new File(html);
try (
FileInputStream fis1 = new FileInputStream(FilenameUtils.normalize(filePath));
FileInputStream fis = new FileInputStream(htmlFile);
) {
Source template = new StreamSource(fis1); Source template = new StreamSource(fis1);
Date date = new Date();
String path = request.getSession().getServletContext().getRealPath("/");
String subPath = path.substring(0, path.indexOf(File.separator) + 1);
String dir = subPath + "check";
String html = subPath + "check" + File.separator + "task_"
+ date.getTime() + ".html";
File dirFile = new File(dir); File dirFile = new File(dir);
if (!dirFile.exists()) { if (!dirFile.exists()) {
dirFile.mkdirs(); dirFile.mkdirs();
} }
Result result = new StreamResult(html); Result result = new StreamResult(html);
TransformerFactory transformerFactory = TransformerFactory.newInstance(); TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = transformerFactory.newTransformer(template); Transformer transformer = transformerFactory.newTransformer(template);
transformer.transform(source, result); transformer.transform(source, result);
File htmlFile = new File(html);
FileInputStream fis = new FileInputStream(htmlFile);
String data = IOUtils.toString(fis, StandardCharsets.UTF_8); String data = IOUtils.toString(fis, StandardCharsets.UTF_8);
fis.close();
if (htmlFile.exists()) { if (htmlFile.exists()) {
htmlFile.delete(); htmlFile.delete();
} }
......
...@@ -2108,12 +2108,13 @@ public class PlanTaskServiceImpl implements IPlanTaskService { ...@@ -2108,12 +2108,13 @@ public class PlanTaskServiceImpl implements IPlanTaskService {
} }
public static byte[] file2byte(File file) { public static byte[] file2byte(File file) {
try { try (
FileInputStream in = new FileInputStream(file); FileInputStream in = new FileInputStream(file);
) {
//当文件没有结束时,每次读取一个字节显示 //当文件没有结束时,每次读取一个字节显示
byte[] data = new byte[in.available()]; byte[] data = new byte[in.available()];
in.read(data); in.read(data);
in.close();
return data; return data;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
......
...@@ -475,37 +475,26 @@ public class FileHelper { ...@@ -475,37 +475,26 @@ public class FileHelper {
} }
public static void nioTransferCopy(File source, File target) { public static void nioTransferCopy(File source, File target) {
FileChannel in = null; try (
FileChannel out = null; FileInputStream inStream = new FileInputStream(source);
FileInputStream inStream = null; FileOutputStream outStream = new FileOutputStream(target);
FileOutputStream outStream = null; FileChannel in = inStream.getChannel();
try { FileChannel out = outStream.getChannel();
inStream = new FileInputStream(source); ) {
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
in.transferTo(0, in.size(), out); in.transferTo(0, in.size(), out);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
} }
} }
private static boolean nioBufferCopy(File source, File target) { private static boolean nioBufferCopy(File source, File target) {
FileChannel in = null; try (
FileChannel out = null; FileInputStream inStream = new FileInputStream(source);
FileInputStream inStream = null; FileOutputStream outStream = new FileOutputStream(target);
FileOutputStream outStream = null; FileChannel in = inStream.getChannel();
try { FileChannel out = outStream.getChannel();
inStream = new FileInputStream(source); ) {
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4096); ByteBuffer buffer = ByteBuffer.allocate(4096);
while (in.read(buffer) != -1) { while (in.read(buffer) != -1) {
buffer.flip(); buffer.flip();
...@@ -515,22 +504,16 @@ public class FileHelper { ...@@ -515,22 +504,16 @@ public class FileHelper {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} finally {
close(inStream);
close(in);
close(outStream);
close(out);
} }
return true; return true;
} }
public static void customBufferStreamCopy(File source, File target) { public static void customBufferStreamCopy(File source, File target) {
InputStream fis = null; try (
OutputStream fos = null; InputStream fis = new FileInputStream(source);
try { OutputStream fos = new FileOutputStream(target);
fis = new FileInputStream(source); ) {
fos = new FileOutputStream(target);
byte[] buf = new byte[4096]; byte[] buf = new byte[4096];
int i; int i;
while ((i = fis.read(buf)) != -1) { while ((i = fis.read(buf)) != -1) {
...@@ -538,9 +521,6 @@ public class FileHelper { ...@@ -538,9 +521,6 @@ public class FileHelper {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
close(fis);
close(fos);
} }
} }
......
...@@ -18,11 +18,9 @@ import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; ...@@ -18,11 +18,9 @@ import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import java.io.BufferedReader; import java.io.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
...@@ -395,31 +393,32 @@ public class HttpUtil { ...@@ -395,31 +393,32 @@ public class HttpUtil {
/** /**
* 发送 delete请求带请求头 * 发送 delete请求带请求头
*/ */
public static String sendHttpDeleteJsonWithHeader(String httpUrl, String paramsJson, Map<String, String> headerMap) { public static String sendHttpDeleteJsonWithHeader(String httpUrl, String paramsJson, Map<String, String> headerMap) throws IOException {
StringBuffer content = new StringBuffer(); StringBuffer content = new StringBuffer();
try { URL url = new URL(httpUrl);
URL url = new URL(httpUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("DELETE");
connection.setRequestMethod("DELETE"); connection.setDoInput(true);
connection.setDoInput(true); connection.setDoOutput(true);
connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); for (Map.Entry<String, String> entry : headerMap.entrySet()) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue());
connection.setRequestProperty(entry.getKey(), entry.getValue()); }
} try (
PrintWriter printWriter = new PrintWriter(connection.getOutputStream()); OutputStream outputStream = connection.getOutputStream();
InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(inputStreamReader);
PrintWriter printWriter = new PrintWriter(outputStream);
) {
printWriter.write(paramsJson); printWriter.write(paramsJson);
printWriter.flush(); printWriter.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
content.append(line); content.append(line);
} }
br.close();
connection.disconnect(); connection.disconnect();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
} }
return content.toString(); return content.toString();
} }
......
...@@ -82,8 +82,7 @@ public class WordHtml implements AbstractHtml { ...@@ -82,8 +82,7 @@ public class WordHtml implements AbstractHtml {
private static void convertDoc2Html(InputStream is, String outPutFile) private static void convertDoc2Html(InputStream is, String outPutFile)
throws TransformerException, IOException, ParserConfigurationException { throws TransformerException, IOException, ParserConfigurationException {
StreamResult streamResult = null; StreamResult streamResult = null;
ByteArrayOutputStream out = null; try (ByteArrayOutputStream out = new ByteArrayOutputStream();) {
try {
String[] outPutFiles = outPutFile.split("\\\\"); String[] outPutFiles = outPutFile.split("\\\\");
outPutFiles = outPutFiles[outPutFiles.length - 1].split("/"); outPutFiles = outPutFiles[outPutFiles.length - 1].split("/");
final String root = outPutFiles[outPutFiles.length - 1]; final String root = outPutFiles[outPutFiles.length - 1];
...@@ -105,19 +104,18 @@ public class WordHtml implements AbstractHtml { ...@@ -105,19 +104,18 @@ public class WordHtml implements AbstractHtml {
if (pics != null) { if (pics != null) {
for (int i = 0; i < pics.size(); i++) { for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i); Picture pic = (Picture) pics.get(i);
try { try (
FileOutputStream fileOutputStream = new FileOutputStream(outPutFile + "/" + pic.suggestFullFileName());
) {
// 指定doc文档中转换后图片保存的路径 // 指定doc文档中转换后图片保存的路径
pic.writeImageContent( pic.writeImageContent(fileOutputStream);
new FileOutputStream(outPutFile + "/" + pic.suggestFullFileName()));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
// #end save pictures // #end save pictures
out = new ByteArrayOutputStream();
streamResult = new StreamResult(out); streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance(); TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// 创建执行从 Source 到 Result 的复制的新 Transformer。 // 创建执行从 Source 到 Result 的复制的新 Transformer。
...@@ -133,10 +131,8 @@ public class WordHtml implements AbstractHtml { ...@@ -133,10 +131,8 @@ public class WordHtml implements AbstractHtml {
FileHelper.writeFile(content, outPutFile + ".html"); FileHelper.writeFile(content, outPutFile + ".html");
// FileHelper.parseCharset(outPutFile + ".html"); // FileHelper.parseCharset(outPutFile + ".html");
// System.out.println(new String(out.toByteArray())); // System.out.println(new String(out.toByteArray()));
} finally { } catch (IOException e) {
if (null != out) { e.printStackTrace();
out.close();
}
} }
} }
...@@ -195,44 +191,26 @@ public class WordHtml implements AbstractHtml { ...@@ -195,44 +191,26 @@ public class WordHtml implements AbstractHtml {
public static void xml2Ttml(String docPath, String xsltPath, String hrmlPath){ public static void xml2Ttml(String docPath, String xsltPath, String hrmlPath){
FileInputStream fis= null; try (
FileInputStream fis1= null; //创建XML的文件输入流
try { FileInputStream fis = new FileInputStream(docPath);
//创建XML的文件输入流 //创建XSL文件的输入流
fis = new FileInputStream(docPath); FileInputStream fis1 = new FileInputStream(xsltPath);
Source source=new StreamSource(fis); PrintStream stm = new PrintStream(hrmlPath);
) {
//创建XSL文件的输入流 Source source = new StreamSource(fis);
fis1 = new FileInputStream(xsltPath); Source template = new StreamSource(fis1);
Source template=new StreamSource(fis1); //讲转换后的结果输出到 stm 中即 F:\123.html
Result result = new StreamResult(stm);
PrintStream stm=new PrintStream(hrmlPath); //根据XSL文件创建准个转换对象
//讲转换后的结果输出到 stm 中即 F:\123.html
Result result=new StreamResult(stm);
//根据XSL文件创建准个转换对象
TransformerFactory transformerFactory = TransformerFactory.newInstance(); TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer= transformerFactory.newTransformer(template); Transformer transformer= transformerFactory.newTransformer(template);
//处理xml进行交换 //处理xml进行交换
transformer.transform(source, result); transformer.transform(source, result);
} catch (FileNotFoundException e) { } catch (TransformerException | IOException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace(); e.printStackTrace();
} finally {
//关闭文件流
try {
if(null != fis1){
fis1.close();
}
if(null != fis){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} }
} }
} }
......
...@@ -109,27 +109,15 @@ public class WordTemplateUtils { ...@@ -109,27 +109,15 @@ public class WordTemplateUtils {
public File getWordFileItem(Map map, String title, String ftlFile,String type) throws IOException { public File getWordFileItem(Map map, String title, String ftlFile,String type) throws IOException {
configuration.setClassForTemplateLoading(this.getClass(), "/ftl"); configuration.setClassForTemplateLoading(this.getClass(), "/ftl");
Template freemarkerTemplate = configuration.getTemplate(ftlFile, "UTF-8"); Template freemarkerTemplate = configuration.getTemplate(ftlFile, "UTF-8");
File file = null; File file = createDoc(map, freemarkerTemplate);
File filepdf = new File("sellPlan.pdf"); File filepdf = new File("sellPlan.pdf");
InputStream fin = null; try (
OutputStream os = null; InputStream fin = new FileInputStream(file);
try { OutputStream os = new FileOutputStream(filepdf);
) {
// 调用工具类的createDoc方法生成Word文档 // 调用工具类的createDoc方法生成Word文档
file = createDoc(map, freemarkerTemplate);
fin = new FileInputStream(file);
os = new FileOutputStream(filepdf);
wordTopdfByAspose(fin, os,type); wordTopdfByAspose(fin, os,type);
return filepdf; return filepdf;
} finally {
if (fin != null) {
fin.close();
}
if (os != null) {
os.close();
}
if (file != null) {
file.delete();
}// 删除临时文件
} }
} }
...@@ -214,24 +202,17 @@ public class WordTemplateUtils { ...@@ -214,24 +202,17 @@ public class WordTemplateUtils {
if (!file.exists()) { if (!file.exists()) {
return ""; return "";
} }
InputStream in = null;
byte[] data = null; byte[] data = null;
try { try (InputStream in = new FileInputStream(file);) {
in = new FileInputStream(file); data = new byte[in.available()];
} catch (FileNotFoundException e1) { in.read(data);
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
} catch (IOException e1) {
e1.printStackTrace(); e1.printStackTrace();
} }
try { return null;
if (null != in) {
data = new byte[in.available()];
in.read(data);
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
} }
} }
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