1.pom.xmljava
<!-- SFTP file travel -->
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-sftp</artifactId>
<version>${sshd.version}</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>${jcraft.version}</version>
</dependency>
<dependency>
<groupId>com.trilead</groupId>
<artifactId>trilead-ssh2</artifactId>
<version>${trilead.version}</version>
</dependency>apache
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.3.2</version>
</dependency>session
1. SftpBeanapp
public class SftpBean {
private String userName;
private String secretKey;
private String host;
private int port;
private String privateKey;ssh
public SftpBean() {
}
public SftpBean(String userName, String secretKey, String host, int port, String privateKey) {
super();
this.userName = userName;
this.secretKey = secretKey;
this.host = host;
this.port = port;
this.privateKey = privateKey;
}ide
public String getUserName() {
return userName;
}this
public void setUserName(String userName) {
this.userName = userName;
}.net
public String getSecretKey() {
return secretKey;
}excel
public void setSecretKey(String password) {
this.secretKey = password;
}xml
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPrivateKey() {
return privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
}
2.SftpEngine
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import com.bayconnect.superlop.common.constdefine.ConstDefine;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/**
* SFTP engine,which can provide sftpChannel
*/
public final class SftpEngine {
public static final String STRICT_HOST_KEY_CHECKING = "StrictHostKeyChecking";
public static final String PROPERTY_NO = "no";
public static final String CHANNEL_TYPE = "sftp";
private SftpEngine() {
}
/**
* generate Session instance
* @param sftp
* @return
* @throws JSchException
*/
public static Session openSession(SftpBean sftp) throws JSchException {
Session session = null;
try {
String userName = sftp.getUserName();
String password = sftp.getSecretKey();
String host = sftp.getHost();
int port = sftp.getPort();
String privateKey = sftp.getPrivateKey();
JSch jsch = new JSch();
if (!StringUtils.isEmpty(privateKey)) {
jsch.addIdentity(privateKey);
}
session = jsch.getSession(userName,host,port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put(STRICT_HOST_KEY_CHECKING, PROPERTY_NO);
session.setConfig(config);
session.connect();
} catch (Exception e) {
throw new WsRollbackRuntimeException(e);
}
return session;
}
/**
* open channel for SFTP operate
* @param sess
* @return
* @throws JSchException
*/
public static ChannelSftp openChannel(Session sess) throws JSchException {
if (sess == null) {
throw new WsRollbackRuntimeException("please open session before apply channel!");
}
Channel channel = sess.openChannel(CHANNEL_TYPE);
channel.connect();
return (ChannelSftp) channel;
}
/**
* release channel and session
* @param sess
* @param channel
*/
public static void close(Session sess,ChannelSftp channel) {
if (channel != null) {
channel.disconnect();
}
if (sess != null) {
sess.disconnect();
}
}
}
4.SftpUtil
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.IOUtils;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
/**
* file traveling tools
* by SFTP UTIL,we can take CSV && excel file from original to target file system
*/
public final class SftpUtil {
private SftpUtil() {
//placeholder sonar
}
//eg
public static void main(String[] args) throws SftpException, IOException, JSchException {
String userName = "sftp";
String pass = "sftp";
String host = "127.0.0.1";
int port = 22;
String privateKey = "";
String srcFile = "/orgfile/術語庫v1.csv";
SftpBean srcBean = new SftpBean(userName,pass,host,port,privateKey);
String folder = "/file";
SftpBean tarBean = new SftpBean(userName,pass,host,port,privateKey);
try {
move(srcFile,srcBean,folder,tarBean);
} catch (JSchException e) {
Logger.info("file travel failed!",e);
}
String tarFolder = "/market-data";
String tarFile = "tpo.csv";
final InputStream in = getInputStream(tarFolder,tarFile,srcBean);
List<Map<String,String>> csvList = new ArrayList<>();
List<String> stringList = org.apache.commons.io.IOUtils.readLines(in, Charsets.toCharset(StandardCharsets.UTF_8));
for (int i = 0; i < stringList.size(); i++) {
String stringLine = stringList.get(i);
if (CheckUtil.isNull(stringList.get(i))) {
continue;
}
String[] strings = stringLine.split(",");
Map<String, String> linkedMap = new LinkedHashMap<>();
for (int j = 1; j <= strings.length; j++) {
linkedMap.put(StringUtil.valueOf(j), strings[j - 1]);
}
csvList.add(linkedMap);
}
}
private static InputStream getInputStream(String sftpPath,String fileName,SftpBean sftpBean) throws SftpException, JSchException {
Session sess = SftpEngine.openSession(sftpBean);
ChannelSftp sftp = SftpEngine.openChannel(sess);
if (sftpPath != null && !"".equals(sftpPath)) {
sftp.cd(sftpPath);
}
InputStream is = sftp.get(fileName);
return is;
}
/**
* file move
* @param srcFile
* @param srcBean
* @param tarFolder
* @param tarBean
* @throws SftpException
* @throws IOException
* @throws JSchException
*/
public static boolean move(
String srcFile,
SftpBean srcBean,
String tarFolder,
SftpBean tarBean) throws SftpException, IOException, JSchException {
int folderEnding = srcFile.lastIndexOf(FileDefine.FILE_PATH_REVERSE);
String srcFolder = srcFile.substring(0, folderEnding + 1);
String srcFileName = srcFile.substring(folderEnding + 1);
//download
byte[] fileArray = download(srcFolder,srcFileName,srcBean);
//upload
ByteArrayInputStream bais = new ByteArrayInputStream(fileArray);
InputStream in = new BufferedInputStream(bais);
upload(tarFolder,srcFileName,tarBean,in);
return true;
}
/**
* File stream upload
* @param directory
* @param sftpFileName
* @param tarBean
* @param input
* @return
* @throws JSchException
* @throws SftpException
*/
public static boolean upload(
String directory,
String sftpFileName,
SftpBean tarBean,
InputStream input) throws JSchException, SftpException {
//get session
Session sess = SftpEngine.openSession(tarBean);
if (sess == null) {
throw new WsRollbackRuntimeException(MessageDefine.OPEN_SESSION_FAILED);
}
//open SFTP channel
ChannelSftp sftp = SftpEngine.openChannel(sess);
if (sftp == null) {
throw new WsRollbackRuntimeException(MessageDefine.OPEN_CHANNEL_FAILED);
}
//please check the directory is accessing for the account
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
sftp.put(input, sftpFileName);
//finally release resource
SftpEngine.close(sess, sftp);
return true;
}
/**
* download the source file and store as a named file
* @param directory
* @param downloadFile
* @param saveFile
* @param srcBean
* @throws JSchException
* @throws SftpException
* @throws FileNotFoundException
*/
public static void download(
String directory,
String downloadFile,
String saveFile,
SftpBean srcBean) throws JSchException, SftpException, FileNotFoundException {
//get session
Session sess = SftpEngine.openSession(srcBean);
if (sess == null) {
throw new WsRollbackRuntimeException(MessageDefine.OPEN_SESSION_FAILED);
}
//open SFTP channel
ChannelSftp sftp = SftpEngine.openChannel(sess);
if (sftp == null) {
throw new WsRollbackRuntimeException(MessageDefine.OPEN_CHANNEL_FAILED);
}
File file = null;
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
file = FileUtil.newFile(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
//finally release resource
SftpEngine.close(sess, sftp);
}
/**
* download the source file as a byte array
* @param directory
* @param downloadFile
* @param srcBean
* @return
* @throws SftpException
* @throws IOException
* @throws JSchException
*/
public static byte[] download(
String directory,
String downloadFile,
SftpBean srcBean) throws SftpException, IOException, JSchException {
//get session
Session sess = SftpEngine.openSession(srcBean);
if (sess == null) {
throw new WsRollbackRuntimeException(MessageDefine.OPEN_SESSION_FAILED);
}
//open SFTP channel
ChannelSftp sftp = SftpEngine.openChannel(sess);
if (sftp == null) {
throw new WsRollbackRuntimeException(MessageDefine.OPEN_CHANNEL_FAILED);
}
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
//check file exist
if (!isExistsFile(directory,downloadFile,sftp)) {
throw new WsRollbackRuntimeException(MessageDefine.SOURCE_FILE_LOSING);
}
InputStream is = sftp.get(downloadFile);
byte[] fileData = IOUtils.toByteArray(is);
//finally release resource
SftpEngine.close(sess, sftp);
return fileData;
}
/** * check file exist * @param directory * @param fileName * @param sftp * @return * @throws SftpException */ public static boolean isExistsFile(String directory,String fileName,ChannelSftp sftp) throws SftpException { List<String> files = listFiles(directory,sftp); Iterator<String> itor = files.iterator(); while (itor.hasNext()) { String fn = itor.next(); if (!fileName.equals(fn)) { itor.remove(); } } return !files.isEmpty(); } /** * check dir exist * @param path * @param sftp * @return */ public static boolean isExistDir(String path,ChannelSftp sftp){ boolean isExist = false; try { SftpATTRS sftpATTRS = sftp.lstat(path); isExist = true; return sftpATTRS.isDir(); } catch (Exception e) { if (e.getMessage().toLowerCase().equals("no such file")) { isExist = false; } } return isExist; } /** * list files under the path * @param path * @param sftp * @return * @throws SftpException */ public static List<String> listFiles(String path,ChannelSftp sftp) throws SftpException { if (StringUtils.isBlank(path)) { return new ArrayList<>(); } sftp.cd(path); List<String> findFilelist = new ArrayList<>(); ChannelSftp.LsEntrySelector selector = new ChannelSftp.LsEntrySelector() { @Override public int select(ChannelSftp.LsEntry lsEntry) { findFilelist.add(lsEntry.getFilename()); return 0; } }; sftp.ls(path, selector); return findFilelist; } /** * list file attribute * @param path * @param fileName * @param sftp * @return * @throws SftpException */ public static SftpATTRS listFileAttrs(String path,String fileName,ChannelSftp sftp) throws SftpException { sftp.cd(path); SftpATTRS sftpAttrs = null; List<SftpATTRS> attrList = new ArrayList<>(); ChannelSftp.LsEntrySelector selector = new ChannelSftp.LsEntrySelector() { @Override public int select(ChannelSftp.LsEntry lsEntry) { if (fileName.equals(lsEntry.getFilename())) { attrList.add(lsEntry.getAttrs()); } return 0; } }; sftp.ls(path, selector); if (!attrList.isEmpty()) { sftpAttrs = attrList.get(0); } return sftpAttrs; } }