package com.dhcc.aml.job.business.application.list.utils;
import com.dhcc.aml.job.business.application.list.config.FileProgressMonitor;
import com.dhcc.aml.job.business.application.list.handler.SftpDownloadHandler;
import com.dhcc.aml.job.business.common.log.AmlJobLogger;
import com.dhcc.aml.job.helper.response.BaseResponse;
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
@Configuration
@Component
public class SftpUtil {
Logger logger = LoggerFactory.getLogger(getClass());
@Value("用户")
private String username;
@Value("密码")
private String passward;
@Value("端口")
private int port;
@Value("地址")//199.212.219.27
private String host;
@Value("地址")
private String ip;
@Value("30000")
private int timeOut;
ChannelSftp sftp = null;
/**
* 通过sftp上传文件
*
* @param timeOut
* @throws
*/
public void sendFile(String serverpath, String localpath, int timeOut) throws Exception {
if (serverpath == null || localpath == null) {
return;
}
if (sftp == null || sftp.isClosed()) {
sftp = getChannel();
}
try {
try {
sftp.cd(serverpath);
} catch (SftpException sException) {
if (ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id) {
sftp.mkdir(serverpath);
sftp.cd(serverpath);
}
}
sftp.put(localpath, serverpath);
} catch (SftpException e) {
logger.error("上传文件失败", e);
throw new RuntimeException("平台文件夹创建失败,请检查权限:" + e);
} finally {
disconnect(sftp);
}
}
/**
* 获取平台文件列表
*
* @param srcPath
* @return
* @throws JSchException
* @throws IOException
*/
public List getAllFileNames(String srcPath) throws Exception {
srcPath = srcPath.replace("\\", "/"); //目标文件路径
ChannelSftp sftp = getChannel();
logger.info("开始获取文件文件列表。。。");
List temp = new ArrayList();
try {
Vector vector = sftp.ls(srcPath);
for (Object obj : vector) {
if ((obj instanceof ChannelSftp.LsEntry) && ((ChannelSftp.LsEntry) obj).getFilename().matches("^[A-Za-z0-9_]+.[A-Za-z0-9_]+$")) {
String fileName = ((ChannelSftp.LsEntry) obj).getFilename();
//sftp.get(srcPath+"/"+fileName, dstPath);
temp.add(srcPath + fileName);
}
}
} catch (SftpException e) {
logger.error("获取文件列表失败", e);
} finally {
disconnect(sftp);
}
return temp;
}
/**
* 获取平台的文件
*
* @param srcPath 平台的文件路径
* @param destFilePathFolder 下载文件保存到本地的路径
* @param
* @throws JSchException
* @throws IOException
*/
public boolean downloadFile(String srcPath, String destFilePathFolder) throws JSchException, IOException, SftpException {
logger.info("进来了===");
//格式化路径
srcPath = srcPath.replace("\\", "/");
destFilePathFolder = (destFilePathFolder).replace("\\", "/");
String destFilePath ="";
String destFileSize="";
try {
//本地路径如果不存在,则创建
File destFile = new File(destFilePathFolder);
if (!destFile.exists()) {
logger.info("创建文件夹");
destFile.mkdirs();
}
File srcFile = new File(srcPath);
logger.info("开始获取文件大小");
if (sftp == null || sftp.isClosed()) {
sftp = getChannel();
}
long start = System.currentTimeMillis();
SftpATTRS attr = sftp.stat(srcPath);
//2为小数
destFileSize = String.format("%.2f", attr.getSize() / 1024.0 / 1024.0);
destFilePath = destFile.getAbsolutePath() + File.separator + srcFile.getName();
logger.info("开始下载文件->{}大小->{}MB,本地存放地址->{}", srcPath, destFileSize, destFilePath);
sftp.get(srcPath, destFile.getAbsolutePath());
long end = System.currentTimeMillis();
logger.info("文件->{}下载耗时{}分钟", srcPath, (end - start) / 1000.0 / 60.0);
return true;
} catch (Exception e) {
//获取已经下载文件的大小
File file = new File(destFilePath);
if (file.exists()) {
String fileSize = String.format("%.2f", file.length() / 1024.0 / 1024.0);
logger.error("当前下载文件->{}已经下载{}MB,总大小{}MB", srcPath, fileSize, destFileSize);
}
logger.error("下载异常", e);
if(e.getMessage().contains("Connection refused")) {
AmlJobLogger.log("连接名单厂商服务被拒绝,请检查我们的访问权限",e);
}else if(e.getMessage().contains("Read timed out")) {
AmlJobLogger.log("连接名单厂商服务超时,请检查我们的网络是否稳定,稍后再试一次",e);
}else if(e.getMessage().contains("SftpException")) {
AmlJobLogger.log("连接到名单厂商服务器,网络不稳定下载失败",e);
}
} finally {
disconnect(sftp);
}
return false;
}
/**
* 获取平台的文件
*
* @param srcPath 平台的文件路径
* @param dstPathFolder 文件夹路径
* @throws JSchException
* @throws IOException
*/
public boolean downloadFileMonitor(String srcPath, String dstPathFolder) throws JSchException, IOException, SftpException {
srcPath = srcPath.replace("\\", "/");
dstPathFolder = dstPathFolder.replace("\\", "/");
try {
//本地路径如果不存在,则创建
File destfile = new File(dstPathFolder);
File srcfile = new File(srcPath);
if (!destfile.exists()) {
destfile.mkdirs();
}
long start = System.currentTimeMillis();
if (sftp == null || sftp.isClosed()) {
sftp = getChannel();
}
SftpATTRS attr = sftp.stat(srcPath);
//2为小数
String fileSize = String.format("%.2f", attr.getSize() / 1024.0 / 1024.0);
logger.info("开始下载文件->{}大小->{}MB,本地存放地址->{}", srcPath, fileSize, dstPathFolder);
System.out.println(dstPathFolder + File.separator + srcfile.getName());
OutputStream out = new FileOutputStream(dstPathFolder + File.separator + srcfile.getName());
//添加回调函数监控进度
InputStream is = sftp.get(srcPath, new FileProgressMonitor());
byte[] buff = new byte[1024 * 5];
int read;
if (is != null) {
logger.info("Start to read input stream");
do {
read = is.read(buff, 0, buff.length);