package jalview.ftp; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.SocketException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; public class FtpClient { public static boolean authenticateUser(FTPClient ftpClient, String username, String password) { boolean loggedIn = false; try { loggedIn = ftpClient.login(username, password); } catch (IOException e) { e.printStackTrace(); } disconectFTP(ftpClient); return loggedIn; } public static FTPClient getFtpClient(String serverHost) { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(serverHost); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ftpClient; } public static void disconectFTP(FTPClient ftpClient) { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } public static void listDirectory(FTPClient ftpClient, String parentDir, String currentDir, int level) throws IOException { String dirToList = parentDir; if (!currentDir.equals("")) { dirToList += "/" + currentDir; } FTPFile[] subFiles = ftpClient.listFiles(dirToList); if (subFiles != null && subFiles.length > 0) { for (FTPFile aFile : subFiles) { String currentFileName = aFile.getName(); if (currentFileName.equals(".") || currentFileName.equals("..")) { // skip parent directory and directory itself continue; } for (int i = 0; i < level; i++) { System.out.print("\t"); } if (aFile.isDirectory()) { System.out.println("[" + currentFileName + "]"); listDirectory(ftpClient, dirToList, currentFileName, level + 1); } else { System.out.println(currentFileName); } } } } public static boolean downloadFile(FTPClient client, String remoteFile, String local) { boolean success = false; File downloadFile = new File(local); OutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream( downloadFile)); success = client.retrieveFile(remoteFile, outputStream); } catch (IOException e) { e.printStackTrace(); } finally { try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } if (success) { System.out.println(remoteFile + " has been downloaded successfully."); } return success; } }