List of usage examples for org.apache.commons.net.ftp FTPClient listFiles
public FTPFile[] listFiles() throws IOException
From source file:com.thebigbang.ftpclient.FTPOperation.java
/** * will force keep the device turned on for all the operation duration. * @param params/* ww w .j a v a2 s . com*/ * @return */ @SuppressLint("Wakelock") @SuppressWarnings("deprecation") @Override protected Boolean doInBackground(FTPBundle... params) { Thread.currentThread().setName("FTPOperationWorker"); for (final FTPBundle bundle : params) { FTPClient ftp = new FTPClient(); PowerManager pw = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); WakeLock w = pw.newWakeLock(PowerManager.FULL_WAKE_LOCK, "FTP Client"); try { // setup ftp connection: InetAddress addr = InetAddress.getByName(bundle.FTPServerHost); //set here the timeout. TimeoutThread timeout = new TimeoutThread(_timeOut, new FTPTimeout() { @Override public void Occurred(TimeoutException e) { bundle.Exception = e; bundle.OperationStatus = FTPOperationStatus.Failed; publishProgress(bundle); } }); timeout.start(); ftp.connect(addr, bundle.FTPServerPort); int reply = ftp.getReplyCode(); timeout.Stop(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("connection refuse"); } ftp.login(bundle.FTPCredentialUsername, bundle.FTPCredentialPassword); if (bundle.OperationType == FTPOperationType.Connect) { bundle.OperationStatus = FTPOperationStatus.Succed; publishProgress(bundle); continue; } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); w.acquire(); // then switch between enum of operation types. if (bundle.OperationType == FTPOperationType.RetrieveFilesFoldersList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FilesOnCurrentPath = ftp.listFiles(); bundle.FoldersOnCurrentPath = ftp.listDirectories(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.RetrieveFolderList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FoldersOnCurrentPath = ftp.listDirectories(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.RetrieveFileList) { ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); bundle.FilesOnCurrentPath = ftp.listFiles(); bundle.OperationStatus = FTPOperationStatus.Succed; } else if (bundle.OperationType == FTPOperationType.GetData) { String finalFPFi = bundle.LocalFilePathName; // The remote filename to be downloaded. if (bundle.LocalWorkingDirectory != null && bundle.LocalWorkingDirectory != "") { File f = new File(bundle.LocalWorkingDirectory); f.mkdirs(); finalFPFi = bundle.LocalWorkingDirectory + finalFPFi; } FileOutputStream fos = new FileOutputStream(finalFPFi); // Download file from FTP server String finalFileN = bundle.RemoteFilePathName; if (bundle.RemoteWorkingDirectory != null && bundle.RemoteWorkingDirectory != "") { finalFileN = bundle.RemoteWorkingDirectory + finalFileN; } boolean b = ftp.retrieveFile(finalFileN, fos); if (b) bundle.OperationStatus = FTPOperationStatus.Succed; else bundle.OperationStatus = FTPOperationStatus.Failed; fos.close(); } else if (bundle.OperationType == FTPOperationType.SendData) { InputStream istr = new FileInputStream(bundle.LocalFilePathName); ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory); Boolean b = ftp.storeFile(bundle.RemoteFilePathName, istr); istr.close(); if (b) bundle.OperationStatus = FTPOperationStatus.Succed; else bundle.OperationStatus = FTPOperationStatus.Failed; } else if (bundle.OperationType == FTPOperationType.DeleteData) { throw new IOException("DeleteData is Not yet implemented"); } ftp.disconnect(); // then finish/return. //publishProgress(bundle); } catch (IOException e) { e.printStackTrace(); bundle.Exception = e; bundle.OperationStatus = FTPOperationStatus.Failed; } try { w.release(); } catch (RuntimeException ex) { ex.printStackTrace(); } publishProgress(bundle); } return true; }
From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * find a suitable name for local and remote temporary file *//*from w w w .ja v a2 s.com*/ private File findFileName(FTPClient ftp) { FTPFile[] theFiles = null; final int maxIterations = 1000; for (int counter = 1; counter < maxIterations; counter++) { File localFile = FILE_UTILS.createTempFile("ant" + Integer.toString(counter), ".tmp", null, false, false); String fileName = localFile.getName(); boolean found = false; try { if (theFiles == null) { theFiles = ftp.listFiles(); } for (int counter2 = 0; counter2 < theFiles.length; counter2++) { if (theFiles[counter2] != null && theFiles[counter2].getName().equals(fileName)) { found = true; break; } } } catch (IOException ioe) { throw new BuildException(ioe, getLocation()); } if (!found) { localFile.deleteOnExit(); return localFile; } } return null; }
From source file:net.yacy.grid.io.assets.FTPStorageFactory.java
public FTPStorageFactory(String server, int port, String username, String password, boolean deleteafterread) throws IOException { this.server = server; this.username = username == null ? "" : username; this.password = password == null ? "" : password; this.port = port; this.deleteafterread = deleteafterread; this.ftpClient = new Storage<byte[]>() { @Override//w w w . j a v a2 s.c om public void checkConnection() throws IOException { return; } private FTPClient initConnection() throws IOException { FTPClient ftp = new FTPClient(); ftp.setDataTimeout(3000); ftp.setConnectTimeout(20000); if (FTPStorageFactory.this.port < 0 || FTPStorageFactory.this.port == DEFAULT_PORT) { ftp.connect(FTPStorageFactory.this.server); } else { ftp.connect(FTPStorageFactory.this.server, FTPStorageFactory.this.port); } ftp.enterLocalPassiveMode(); // the server opens a data port to which the client conducts data transfers int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { if (ftp != null) try { ftp.disconnect(); } catch (Throwable ee) { } throw new IOException("bad connection to ftp server: " + reply); } if (!ftp.login(FTPStorageFactory.this.username, FTPStorageFactory.this.password)) { if (ftp != null) try { ftp.disconnect(); } catch (Throwable ee) { } throw new IOException("login failure"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.setBufferSize(8192); return ftp; } @Override public StorageFactory<byte[]> store(String path, byte[] asset) throws IOException { long t0 = System.currentTimeMillis(); FTPClient ftp = initConnection(); try { long t1 = System.currentTimeMillis(); String file = cdPath(ftp, path); long t2 = System.currentTimeMillis(); ftp.enterLocalPassiveMode(); boolean success = ftp.storeFile(file, new ByteArrayInputStream(asset)); long t3 = System.currentTimeMillis(); if (!success) throw new IOException("storage to path " + path + " was not successful (storeFile=false)"); Data.logger.debug("FTPStorageFactory.store ftp store successfull: check connection = " + (t1 - t0) + ", cdPath = " + (t2 - t1) + ", store = " + (t3 - t2)); } catch (IOException e) { throw e; } finally { if (ftp != null) try { ftp.disconnect(); } catch (Throwable ee) { } } return FTPStorageFactory.this; } @Override public Asset<byte[]> load(String path) throws IOException { FTPClient ftp = initConnection(); ByteArrayOutputStream baos = null; byte[] b = null; try { String file = cdPath(ftp, path); baos = new ByteArrayOutputStream(); ftp.retrieveFile(file, baos); b = baos.toByteArray(); if (FTPStorageFactory.this.deleteafterread) try { boolean deleted = ftp.deleteFile(file); FTPFile[] remaining = ftp.listFiles(); if (remaining.length == 0) { ftp.cwd("/"); if (path.startsWith("/")) path = path.substring(1); int p = path.indexOf('/'); if (p > 0) path = path.substring(0, p); ftp.removeDirectory(path); } } catch (Throwable e) { Data.logger.warn("FTPStorageFactory.load failed to remove asset " + path, e); } } catch (IOException e) { throw e; } finally { if (ftp != null) try { ftp.disconnect(); } catch (Throwable ee) { } } return new Asset<byte[]>(FTPStorageFactory.this, b); } @Override public void close() { } private String cdPath(FTPClient ftp, String path) throws IOException { int success_code = ftp.cwd("/"); if (success_code >= 300) throw new IOException("cannot cd into " + path + ": " + success_code); if (path.length() == 0 || path.equals("/")) return ""; if (path.charAt(0) == '/') path = path.substring(1); // we consider that all paths are absolute to / (home) int p; while ((p = path.indexOf('/')) > 0) { String dir = path.substring(0, p); int code = ftp.cwd(dir); if (code >= 300) { // path may not exist, try to create the path boolean success = ftp.makeDirectory(dir); if (!success) throw new IOException("unable to create directory " + dir + " for path " + path); code = ftp.cwd(dir); if (code >= 300) throw new IOException("unable to cwd into directory " + dir + " for path " + path); } path = path.substring(p + 1); } return path; } }; }
From source file:nz.govt.natlib.ndha.common.FileUtils.java
public static void removeFTPDirectory(FTPClient ftpClient, String directoryName) { try {// w w w .ja v a 2 s . c o m ftpClient.changeWorkingDirectory(directoryName); for (FTPFile file : ftpClient.listFiles()) { if (file.isDirectory()) { FileUtils.removeFTPDirectory(ftpClient, file.getName()); } else { log.debug("Deleting " + file.getName()); ftpClient.deleteFile(file.getName()); } } ftpClient.changeWorkingDirectory(directoryName); ftpClient.changeToParentDirectory(); log.debug("Deleting " + directoryName); ftpClient.removeDirectory(directoryName); } catch (Exception ex) { } }
From source file:org.alfresco.bm.file.FtpTestFileService.java
/** * Does a listing of files on the FTP server *///from w w w. ja v a2 s. c om @Override protected List<FileData> listRemoteFiles() { // Get a list of files from the FTP server FTPClient ftp = null; FTPFile[] ftpFiles = new FTPFile[0]; try { ftp = getFTPClient(); if (!ftp.changeWorkingDirectory(ftpPath)) { throw new IOException("Failed to change directory (leading '/' could be a problem): " + ftpPath); } ftpFiles = ftp.listFiles(); } catch (IOException e) { throw new RuntimeException("FTP file listing failed: " + this, e); } finally { try { if (null != ftp) { ftp.logout(); ftp.disconnect(); } } catch (IOException e) { logger.warn("Failed to close FTP connection: " + e.getMessage()); } } // Index each of the files List<FileData> remoteFileDatas = new ArrayList<FileData>(ftpFiles.length); for (FTPFile ftpFile : ftpFiles) { String ftpFilename = ftpFile.getName(); // Watch out for . and .. if (ftpFilename.equals(".") || ftpFilename.equals("..")) { continue; } String ftpExtension = FileData.getExtension(ftpFilename); long ftpSize = ftpFile.getSize(); FileData remoteFileData = new FileData(); remoteFileData.setRemoteName(ftpFilename); remoteFileData.setExtension(ftpExtension); remoteFileData.setSize(ftpSize); remoteFileDatas.add(remoteFileData); } // Done return remoteFileDatas; }
From source file:org.alfresco.filesys.FTPServerTest.java
/** * Simple negative test that connects to the inbuilt ftp server and attempts to * log on with the wrong password./* ww w . j a va 2 s . co m*/ * * @throws Exception */ public void testFTPConnectNegative() throws Exception { logger.debug("Start testFTPConnectNegative"); FTPClient ftp = connectClient(); try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, "garbage"); assertFalse("admin login successful", login); // now attempt to list the files and check that the command does not // succeed FTPFile[] files = ftp.listFiles(); assertNotNull(files); assertTrue(files.length == 0); reply = ftp.getReplyCode(); assertTrue(FTPReply.isNegativePermanent(reply)); } finally { ftp.disconnect(); } }
From source file:org.alfresco.filesys.FTPServerTest.java
/** * Test CWD for FTP server//from ww w . ja v a2 s.co m * * @throws Exception */ public void testCWD() throws Exception { logger.debug("Start testCWD"); FTPClient ftp = connectClient(); try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login successful", login); FTPFile[] files = ftp.listFiles(); reply = ftp.getReplyCode(); assertTrue(FTPReply.isPositiveCompletion(reply)); assertTrue(files.length == 1); boolean foundAlfresco = false; for (FTPFile file : files) { logger.debug("file name=" + file.getName()); assertTrue(file.isDirectory()); if (file.getName().equalsIgnoreCase("Alfresco")) { foundAlfresco = true; } } assertTrue(foundAlfresco); // Change to Alfresco Dir that we know exists reply = ftp.cwd("/Alfresco"); assertTrue(FTPReply.isPositiveCompletion(reply)); // relative path with space char reply = ftp.cwd("Data Dictionary"); assertTrue(FTPReply.isPositiveCompletion(reply)); // non existant absolute reply = ftp.cwd("/Garbage"); assertTrue(FTPReply.isNegativePermanent(reply)); reply = ftp.cwd("/Alfresco/User Homes"); assertTrue(FTPReply.isPositiveCompletion(reply)); // Wild card reply = ftp.cwd("/Alfresco/User*Homes"); assertTrue("unable to change to /Alfresco User*Homes/", FTPReply.isPositiveCompletion(reply)); // // Single char pattern match // reply = ftp.cwd("/Alfre?co"); // assertTrue("Unable to match single char /Alfre?co", FTPReply.isPositiveCompletion(reply)); // two level folder reply = ftp.cwd("/Alfresco/Data Dictionary"); assertTrue("unable to change to /Alfresco/Data Dictionary", FTPReply.isPositiveCompletion(reply)); // go up one reply = ftp.cwd(".."); assertTrue("unable to change to ..", FTPReply.isPositiveCompletion(reply)); reply = ftp.pwd(); ftp.getStatus(); assertTrue("unable to get status", FTPReply.isPositiveCompletion(reply)); // check we are at the correct point in the tree reply = ftp.cwd("Data Dictionary"); assertTrue(FTPReply.isPositiveCompletion(reply)); } finally { ftp.disconnect(); } }
From source file:org.alfresco.filesys.FTPServerTest.java
/** * Test CRUD for FTP server// w ww . j a v a 2 s .com * * @throws Exception */ public void testCRUD() throws Exception { final String PATH1 = "FTPServerTest"; final String PATH2 = "Second part"; logger.debug("Start testFTPCRUD"); FTPClient ftp = connectClient(); try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login successful", login); reply = ftp.cwd("/Alfresco/User Homes"); assertTrue(FTPReply.isPositiveCompletion(reply)); // Delete the root directory in case it was left over from a previous test run try { ftp.removeDirectory(PATH1); } catch (IOException e) { // ignore this error } // make root directory ftp.makeDirectory(PATH1); ftp.cwd(PATH1); // make sub-directory in new directory ftp.makeDirectory(PATH2); ftp.cwd(PATH2); // List the files in the new directory FTPFile[] files = ftp.listFiles(); assertTrue("files not empty", files.length == 0); // Create a file String FILE1_CONTENT_1 = "test file 1 content"; String FILE1_NAME = "testFile1.txt"; ftp.appendFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8"))); // Get the new file FTPFile[] files2 = ftp.listFiles(); assertTrue("files not one", files2.length == 1); InputStream is = ftp.retrieveFileStream(FILE1_NAME); String content = inputStreamToString(is); assertEquals("Content is not as expected", content, FILE1_CONTENT_1); ftp.completePendingCommand(); // Update the file contents String FILE1_CONTENT_2 = "That's how it is says Pooh!"; ftp.storeFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8"))); InputStream is2 = ftp.retrieveFileStream(FILE1_NAME); String content2 = inputStreamToString(is2); assertEquals("Content is not as expected", FILE1_CONTENT_2, content2); ftp.completePendingCommand(); // now delete the file we have been using. assertTrue(ftp.deleteFile(FILE1_NAME)); // negative test - file should have gone now. assertFalse(ftp.deleteFile(FILE1_NAME)); } finally { // clean up tree if left over from previous run ftp.disconnect(); } }
From source file:org.alfresco.filesys.FTPServerTest.java
/** * Test Setting the modification time FTP server * * @throws Exception//from www.j a v a2 s . c o m */ public void testModificationTime() throws Exception { final String PATH1 = "FTPServerTest"; final String PATH2 = "ModificationTime"; logger.debug("Start testModificationTime"); FTPClient ftp = connectClient(); try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login successful", login); reply = ftp.cwd("/Alfresco/User Homes"); assertTrue(FTPReply.isPositiveCompletion(reply)); // Delete the root directory in case it was left over from a previous test run try { ftp.removeDirectory(PATH1); } catch (IOException e) { // ignore this error } // make root directory ftp.makeDirectory(PATH1); ftp.cwd(PATH1); // make sub-directory in new directory ftp.makeDirectory(PATH2); ftp.cwd(PATH2); // List the files in the new directory FTPFile[] files = ftp.listFiles(); assertTrue("files not empty", files.length == 0); // Create a file String FILE1_CONTENT_1 = "test file 1 content"; String FILE1_NAME = "testFile1.txt"; ftp.appendFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8"))); String pathname = "/Alfresco/User Homes" + "/" + PATH1 + "/" + PATH2 + "/" + FILE1_NAME; logger.debug("set modification time"); // YYYYMMDDhhmmss Time set to 2012 August 30 12:39:05 String olympicTime = "20120830123905"; ftp.setModificationTime(pathname, olympicTime); String extractedTime = ftp.getModificationTime(pathname); // Feature of the commons ftp library ExtractedTime has a "status code" first and is followed by newline chars assertTrue("time not set correctly by explicit set time", extractedTime.contains(olympicTime)); // Get the new file FTPFile[] files2 = ftp.listFiles(); assertTrue("files not one", files2.length == 1); InputStream is = ftp.retrieveFileStream(FILE1_NAME); String content = inputStreamToString(is); assertEquals("Content is not as expected", content, FILE1_CONTENT_1); ftp.completePendingCommand(); // Update the file contents without setting time directly String FILE1_CONTENT_2 = "That's how it is says Pooh!"; ftp.storeFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8"))); InputStream is2 = ftp.retrieveFileStream(FILE1_NAME); String content2 = inputStreamToString(is2); assertEquals("Content is not as expected", FILE1_CONTENT_2, content2); ftp.completePendingCommand(); extractedTime = ftp.getModificationTime(pathname); assertFalse("time not moved on if time not explicitly set", extractedTime.contains(olympicTime)); // now delete the file we have been using. assertTrue(ftp.deleteFile(FILE1_NAME)); // negative test - file should have gone now. assertFalse(ftp.deleteFile(FILE1_NAME)); } finally { // clean up tree if left over from previous run ftp.disconnect(); } }
From source file:org.alinous.ftp.FtpManager.java
public FTPFile[] listFiles(String sessionId) throws IOException { FTPClient ftp = this.instances.get(sessionId).getFtp(); //ftp.enterRemotePassiveMode(); /*int resN = ftp.pasv(); System.out.println(resN);/*from w w w . j a va 2s . c om*/ cur = ftp.getReplyString(); System.out.println(cur); */ FTPFile[] files = ftp.listFiles(); return files; }