Commit 8ffac187 authored by 周亚武's avatar 周亚武

url 文件下载状态监测

parent 8e0a5a58
...@@ -39,7 +39,7 @@ ...@@ -39,7 +39,7 @@
<profiles.active>test</profiles.active> <profiles.active>test</profiles.active>
<profiles.filepath>/tmp</profiles.filepath> <profiles.filepath>/tmp</profiles.filepath>
<profiles.log.level>INFO</profiles.log.level> <profiles.log.level>INFO</profiles.log.level>
<profiles.log.path>/opt/apps/mid-service/logs</profiles.log.path> <profiles.log.path>/opt/app/mid-service/logs</profiles.log.path>
<profiles.config.path>/root/mid.prop</profiles.config.path> <profiles.config.path>/root/mid.prop</profiles.config.path>
<profiles.server.port>80</profiles.server.port> <profiles.server.port>80</profiles.server.port>
<profiles.hcpUrl>http://192.168.0.98:8090/inter/hcpapi/hcpGrabEvaluate</profiles.hcpUrl> <profiles.hcpUrl>http://192.168.0.98:8090/inter/hcpapi/hcpGrabEvaluate</profiles.hcpUrl>
......
package com.mortals.xhx.common.utils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CompletableFuture;
/**
* @author ZYW
* @date 2024-12-24 16:16
*/
public class FileDownloader {
public interface Callback {
void onSuccess();
void onError(Exception e);
}
public static void downloadFileFromUrl(String urlPath, String downloadDir, Callback callback) {
CompletableFuture.runAsync(() -> {
File file = null;
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//设置超时
httpURLConnection.setConnectTimeout(1000 * 30);
//设置请求方式,默认是GET
httpURLConnection.setRequestMethod("GET");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 文件大小
int fileLength = httpURLConnection.getContentLength();
// 控制台打印文件大小
// System.out.println("下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");
// 建立链接从请求中获取数据
URLConnection con = url.openConnection();
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
// 指定文件名称(有需求可以自定义)
String fileFullName = urlPath.split("/")[urlPath.split("/").length - 1];
// 指定存放位置(有需求可以自定义)
String path = downloadDir;
file = new File(path);
// 校验文件夹目录是否存在,不存在就创建一个目录
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[2048];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
// 控制台打印文件下载的百分比情况
// System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
}
// 关闭资源
bin.close();
out.close();
// 成功后调用回调函数
if (callback != null) {
callback.onSuccess();
}
} catch (Exception e) {
// 出错时调用回调函数
if (callback != null) {
callback.onError(e);
}
}
});
}
public static void main(String[] args) {
String url = "http://example.com/somefile.zip"; // 替换为实际的URL
String filename = "somefile.zip"; // 替换为想要保存的文件名
downloadFileFromUrl(url, filename, new Callback() {
@Override
public void onSuccess() {
System.out.println("文件下载成功!");
}
@Override
public void onError(Exception e) {
System.out.println("文件下载出错:" + e.getMessage());
}
});
}
}
...@@ -4,6 +4,7 @@ import cn.hutool.core.io.FileUtil; ...@@ -4,6 +4,7 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil; import cn.hutool.http.HttpUtil;
import com.mortals.framework.common.Rest; import com.mortals.framework.common.Rest;
import com.mortals.xhx.common.code.PrintTypeEnum; import com.mortals.xhx.common.code.PrintTypeEnum;
import com.mortals.xhx.common.utils.FileDownloader;
import com.mortals.xhx.common.utils.PdfUtil; import com.mortals.xhx.common.utils.PdfUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocument;
...@@ -33,92 +34,125 @@ public class UrlPrintComponent extends BasePrintComponent { ...@@ -33,92 +34,125 @@ public class UrlPrintComponent extends BasePrintComponent {
public static String imgs[] = {"jpg", "png", "jpeg", "gif"}; public static String imgs[] = {"jpg", "png", "jpeg", "gif"};
public static String pdf[] = {"pdf"}; public static String pdf[] = {"pdf"};
int downStaus = 0; // 下载文件的状态 0正在下载 1成功 -1失败
// 获取当前系统名称 // 获取当前系统名称
static String osName = System.getProperty("os.name").toLowerCase(); static String osName = System.getProperty("os.name").toLowerCase();
@Override @Override
public Rest<Void> print(ComponentCons cons) { public Rest<Void> print(ComponentCons cons) {
//获取文件后缀 //获取文件后缀
String suffixName = FileUtil.getSuffix(cons.getUrl()); String suffixName = FileUtil.getSuffix(cons.getUrl());
String samplePath = "/root/sourceFile."+suffixName; //源文件下载地址 String samplePath = "/tmp/sourceFile."+suffixName; //源文件下载地址
//通过网络下载附件地址 //通过网络下载附件地址
File file = HttpUtil.downloadFileFromUrl(cons.getUrl(),"/root/sourceFile."+suffixName); // File file = HttpUtil.downloadFileFromUrl(cons.getUrl(),"/tmp/sourceFile."+suffixName);
FileDownloader.downloadFileFromUrl(cons.getUrl(), "/tmp/sourceFile." + suffixName, new FileDownloader.Callback() {
log.info("file name:{}",file.getAbsolutePath()); @Override
log.info("file suffixName:{}", suffixName); public void onSuccess() {
String pdfPath = "/root/target.pdf"; downStaus = 1;
}
@Override
public void onError(Exception e) {
downStaus = -1;
}
});
//判断文件类型是否为doc pdf jpg png 等 while (downStaus == 0){
if (this.isExsitArry(suffixName, word)) { try {
// 根据系统选择执行方法 Thread.sleep(1000);
if (osName.contains("win")) { } catch (InterruptedException e) {
PdfUtil.winWordToPdf(samplePath,pdfPath); throw new RuntimeException(e);
} else if (osName.contains("nux") || osName.contains("nix")) {
pdfPath = "/root/sourceFile.pdf"; //linux下不会指定新文件名称 会以原文件名+.pdf生成一个新文件
PdfUtil.linuxWordToPdf(samplePath,"/root/");
} }
} else if (this.isExsitArry(suffixName, pdf)) {
pdfPath = samplePath;
}else if(this.isExsitArry(suffixName, imgs)){
PdfUtil.imgToPdf(samplePath,pdfPath);
} }
PDDocument document = null; if(downStaus == 1){
try {
// 加载PDF文档
File pdfFile = new File(pdfPath);
document = PDDocument.load(pdfFile);
// 创建一个打印任务 File file = new File("/tmp/sourceFile." + suffixName);
PrinterJob job = PrinterJob.getPrinterJob(); log.info("file name:{}",file.getAbsolutePath());
log.info("file suffixName:{}", suffixName);
String pdfPath = "/tmp/target.pdf";
// 查找并设置打印机 //判断文件类型是否为doc pdf jpg png 等
PrintService defaultPrintService = getPrintService(cons); if (this.isExsitArry(suffixName, word)) {
if (defaultPrintService != null) { // 根据系统选择执行方法
job.setPrintService(defaultPrintService); if (osName.contains("win")) {
}else { PdfUtil.winWordToPdf(samplePath,pdfPath);
return Rest.fail("未找到打印机"); } else if (osName.contains("nux") || osName.contains("nix")) {
pdfPath = "/tmp/sourceFile.pdf"; //linux下不会指定新文件名称 会以原文件名+.pdf生成一个新文件
PdfUtil.linuxWordToPdf(samplePath,"/tmp/");
}
} else if (this.isExsitArry(suffixName, pdf)) {
pdfPath = samplePath;
}else if(this.isExsitArry(suffixName, imgs)){
PdfUtil.imgToPdf(samplePath,pdfPath);
} }
job.setJobName(pdfFile.getName()); PDDocument document = null;
//设置纸张 try {
PDFPrintable pdfPrintable = new PDFPrintable(document); // 加载PDF文档
//设置多页打印 File pdfFile = new File(pdfPath);
Book book = new Book(); document = PDDocument.load(pdfFile);
PageFormat pageFormat = new PageFormat();
Paper paper = getPaper(); // 创建一个打印任务
pageFormat.setPaper(paper); PrinterJob job = PrinterJob.getPrinterJob();
book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
job.setPageable(new PDFPageable(document));
job.setPageable(book); // 查找并设置打印机
job.setCopies(1);//设置打印份数 PrintService defaultPrintService = getPrintService(cons);
if (defaultPrintService != null) {
HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet(); job.setPrintService(defaultPrintService);
pars.add(Sides.ONE_SIDED); // 设置单双页 }else {
pars.add(MediaSizeName.ISO_A4);//默认A4纸打印 downStaus = 0;
// 执行打印 return Rest.fail("未找到打印机");
job.print(pars); }
log.info("打印成功!"); job.setJobName(pdfFile.getName());
return Rest.ok(); //设置纸张
}catch (PrinterException e){ PDFPrintable pdfPrintable = new PDFPrintable(document);
log.error("打印异常", e); //设置多页打印
return Rest.fail("打印异常"); Book book = new Book();
}catch (IOException e){ PageFormat pageFormat = new PageFormat();
log.error("文件处理异常", e); Paper paper = getPaper();
return Rest.fail("文件处理异常"); pageFormat.setPaper(paper);
}finally { book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
if (document != null) { job.setPageable(new PDFPageable(document));
try { job.setPageable(book);
// 关闭PDF文档 job.setCopies(1);//设置打印份数
document.close();
} catch (IOException e) { HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet();
e.printStackTrace(); pars.add(Sides.ONE_SIDED); // 设置单双页
pars.add(MediaSizeName.ISO_A4);//默认A4纸打印
// 执行打印
job.print(pars);
log.info("打印成功!");
downStaus = 0;
return Rest.ok();
}catch (PrinterException e){
log.error("打印异常", e);
downStaus = 0;
return Rest.fail("打印异常");
}catch (IOException e){
log.error("文件处理异常", e);
downStaus = 0;
return Rest.fail("文件处理异常");
}finally {
if (document != null) {
try {
// 关闭PDF文档
document.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
} }
}else {
downStaus = 0;
return Rest.fail("文件下载失败");
} }
......
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