import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.StringTokenizer; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import com.ea.rs4.Logger; import com.ea.rs4.utils.StringUtils; /** * This class is used to upload files to ftp server or get files from ftp server * * @author Leo.Zhou */ public class FtpTool { private static final Logger LOG = new Logger(FtpTool.class.getSimpleName()); private String ip; private int port; private String user; private String pwd; private String remotePath; FTPClient ftpClient; /** * Connect to server * * @param ip * @param port * @param user * @param pwd * @return * @throws FtpException */ public boolean connectServer(String ip, int port, String user, String pwd) throws FtpException { boolean isSuccess = false; try { ftpClient = new FTPClient(); ftpClient.connect(ip, port); ftpClient.login(user, pwd); isSuccess = true; } catch (Exception ex) { LOG.error("Can not connect to remote ftp server"); throw new FtpException(ex); } return isSuccess; } /** * Create directory * * @param dir * @return * @throws FtpException */ private void createDir(String dir) throws FtpException { try { ftpClient.setFileType(FTP.ASCII_FILE_TYPE); StringTokenizer s = new StringTokenizer(dir, "/"); s.countTokens(); String pathName = ""; while (s.hasMoreElements()) { String currentFolder = (String) s.nextElement(); if (currentFolder == null || currentFolder.length() == 0) { continue; } pathName = pathName + (pathName.equals("")?"":"/") + currentFolder; if(!isDirExist(pathName)) { boolean result = ftpClient.makeDirectory(pathName); if(!result) { throw new FtpException(String.format("Permission denied, can not create folder : %s", pathName)); } } } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } catch (IOException e1) { throw new FtpException(e1); } } /** * Check is directory exist * * @param dir * @return * @throws FtpException */ private boolean isDirExist(String dir) { if(StringUtils.isEmpty(dir)) { return true; } String preFolder = null; String lastFolder = null; if(dir.contains("/")) { preFolder = dir.substring(0, dir.lastIndexOf("/")); lastFolder = dir.substring(dir.lastIndexOf("/") + 1, dir.length()); } else { preFolder = ""; lastFolder = dir; } boolean flag = false; try { FTPFile[] ftpFileArr = null; if(preFolder.equals("")) { ftpFileArr = ftpClient.listFiles(); } else { ftpFileArr = ftpClient.listFiles(preFolder); } LOG.debug("Files in top folder : %s", Arrays.toString(ftpFileArr)); for (FTPFile ftpFile : ftpFileArr) { if (ftpFile.isDirectory() && ftpFile.getName().equalsIgnoreCase(lastFolder)) { flag = true; break; } } } catch (IOException e) { flag = false; } return flag; } /** * Upload file to ftp server * * @param remotePath * @param localPath * @param filename * @throws FtpException */ public void uploadFile(String remotePath, File localFile) throws FtpException { try { if (connectServer(getIp(), getPort(), getUser(), getPwd())) { if (!isDirExist(remotePath)) { createDir(remotePath); } if (remotePath.length() != 0) ftpClient.changeWorkingDirectory(remotePath); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); InputStream iStream = null; try { iStream = new FileInputStream(localFile); boolean result = ftpClient.storeFile(localFile.getName(), iStream); if(!result) { LOG.error("Upload file to FTP server failed."); throw new FtpException("Upload file failed."); } } finally { if (iStream != null) { iStream.close(); } } closeServer(); } } catch (IOException ex) { throw new FtpException("Ftp upload file error:", ex); } } /** * Delete FTP file by link * * @param link * @throws FtpException */ public void deleteFileByLink(String link) throws FtpException{ try { if (connectServer(getIp(), getPort(), getUser(), getPwd())) { ftpClient.deleteFile(getRemotePath() + "/" + link); int status = ftpClient.getReplyCode(); LOG.debug("Ftp delete info:"+ftpClient.getReplyString()); if(status == 250) { LOG.debug("Delete file from FTP server success."); } else { LOG.info("Delete file from FTP server failed.FTP status : %s, link : %s", status, link); throw new FtpException(String.format("Delete file from FTP server failed, link : %s, FTP status : %s", link, status)); } closeServer(); } } catch (IOException ex) { throw new FtpException(String.format("Delete file from FTP server failed, link : %s", link)); } } /** * Close ftp server connection * * @throws FtpException */ private void closeServer() throws FtpException { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { throw new FtpException(e); } } } /** * @return */ public String getIp() { return ip; } /** * @return */ public int getPort() { return port; } /** * @return */ public String getPwd() { return pwd; } /** * @return */ public String getUser() { return user; } /** * @param string */ public void setIp(String string) { ip = string; } /** * @param i */ public void setPort(int i) { port = i; } /** * @param string */ public void setPwd(String string) { pwd = string; } /** * @param string */ public void setUser(String string) { user = string; } /** * @return */ public String getRemotePath() { return remotePath; } /** * @param string */ public void setRemotePath(String remotePath) { this.remotePath = remotePath; this.remotePath = this.remotePath.replace("\\", "/"); LOG.debug("Saving path in current system: %s", this.remotePath); } }