Java Code Examples for org.apache.commons.net.ftp.ftpclient#removeDirectory()

The following examples show how to use org.apache.commons.net.ftp.ftpclient#removeDirectory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileUtils.java    From webcurator with Apache License 2.0 7 votes vote down vote up
public static void removeFTPDirectory(FTPClient ftpClient, String directoryName) {
	try {
    	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) {
		
	}
}
 
Example 2
Source File: FTPFileSystem.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method, so that we don't open a new connection when using this
 * method from within another method. Otherwise every API invocation incurs
 * the overhead of opening/closing a TCP connection.
 */
private boolean delete(FTPClient client, Path file, boolean recursive)
    throws IOException {
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  String pathName = absolute.toUri().getPath();
  try {
    FileStatus fileStat = getFileStatus(client, absolute);
    if (fileStat.isFile()) {
      return client.deleteFile(pathName);
    }
  } catch (FileNotFoundException e) {
    //the file is not there
    return false;
  }
  FileStatus[] dirEntries = listStatus(client, absolute);
  if (dirEntries != null && dirEntries.length > 0 && !(recursive)) {
    throw new IOException("Directory: " + file + " is not empty.");
  }
  for (FileStatus dirEntry : dirEntries) {
    delete(client, new Path(absolute, dirEntry.getPath()), recursive);
  }
  return client.removeDirectory(pathName);
}
 
Example 3
Source File: FTPFileSystem.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method, so that we don't open a new connection when using this
 * method from within another method. Otherwise every API invocation incurs
 * the overhead of opening/closing a TCP connection.
 */
private boolean delete(FTPClient client, Path file, boolean recursive)
    throws IOException {
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  String pathName = absolute.toUri().getPath();
  try {
    FileStatus fileStat = getFileStatus(client, absolute);
    if (fileStat.isFile()) {
      return client.deleteFile(pathName);
    }
  } catch (FileNotFoundException e) {
    //the file is not there
    return false;
  }
  FileStatus[] dirEntries = listStatus(client, absolute);
  if (dirEntries != null && dirEntries.length > 0 && !(recursive)) {
    throw new IOException("Directory: " + file + " is not empty.");
  }
  for (FileStatus dirEntry : dirEntries) {
    delete(client, new Path(absolute, dirEntry.getPath()), recursive);
  }
  return client.removeDirectory(pathName);
}
 
Example 4
Source File: FTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean delete(FTPClient ftp, Info info, DeleteParameters params) throws IOException {
	if (Thread.currentThread().isInterrupted()) {
		throw new IOException(FileOperationMessages.getString("IOperationHandler.interrupted")); //$NON-NLS-1$
	}
	URI uri = info.getURI();
	if (info.isDirectory()) {
		if (params.isRecursive()) {
			List<Info> children = list(uri, ftp, LIST_NONRECURSIVE);
			for (Info child: children) {
				delete(ftp, child, params);
			}
			return ftp.removeDirectory(getPath(uri));
		} else {
			throw new IOException(MessageFormat.format(FileOperationMessages.getString("IOperationHandler.cannot_remove_directory"), uri)); //$NON-NLS-1$
		}
	} else {
		return ftp.deleteFile(getPath(uri));
	}
}
 
Example 5
Source File: PooledFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean delete(FTPClient ftp, Info info, DeleteParameters params) throws IOException {
	if (Thread.currentThread().isInterrupted()) {
		throw new IOException(FileOperationMessages.getString("IOperationHandler.interrupted")); //$NON-NLS-1$
	}
	URI uri = info.getURI();
	if (info.isDirectory()) {
		if (params.isRecursive()) {
			List<Info> children = list(uri, ftp, LIST_NONRECURSIVE);
			for (Info child: children) {
				delete(ftp, child, params);
			}
			return ftp.removeDirectory(getPath(uri));
		} else {
			throw new IOException(MessageFormat.format(FileOperationMessages.getString("IOperationHandler.cannot_remove_directory"), uri)); //$NON-NLS-1$
		}
	} else {
		return ftp.deleteFile(getPath(uri));
	}
}
 
Example 6
Source File: FtpFileUtil.java    From hsac-fitnesse-fixtures with Apache License 2.0 6 votes vote down vote up
/**
 * Delete given directory from FTP server (directory must be empty).
 * @param hostName the FTP server host name to connect
 * @param port the port to connect
 * @param userName the user name
 * @param password the password
 * @param remotePath the path to the directory on the FTP to be removed
 * @return true if file has been removed  and false otherwise.
 * @throws RuntimeException in case any exception has been thrown.
 */
public static boolean deleteDirectoryFromFTPServer(String hostName, Integer port, String userName, String password, String remotePath) {
    boolean deleted = false;

    FTPClient ftpClient = new FTPClient();
    String errorMessage = "Could not delete the directory '%s' from FTP server '%s'. Cause: %s";

    try {
        connectAndLoginOnFTPServer(ftpClient, hostName, port, userName, password);
        deleted = ftpClient.removeDirectory(remotePath);
    } catch (IOException ex) {
        throw new RuntimeException(String.format(errorMessage, remotePath, hostName), ex);
    } finally {
        disconnectAndLogoutFromFTPServer(ftpClient, hostName);
    }
    return deleted;
}
 
Example 7
Source File: FTPFileSystem.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method, so that we don't open a new connection when using this
 * method from within another method. Otherwise every API invocation incurs
 * the overhead of opening/closing a TCP connection.
 */
private boolean delete(FTPClient client, Path file, boolean recursive)
    throws IOException {
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  String pathName = absolute.toUri().getPath();
  FileStatus fileStat = getFileStatus(client, absolute);
  if (!fileStat.isDir()) {
    return client.deleteFile(pathName);
  }
  FileStatus[] dirEntries = listStatus(client, absolute);
  if (dirEntries != null && dirEntries.length > 0 && !(recursive)) {
    throw new IOException("Directory: " + file + " is not empty.");
  }
  if (dirEntries != null) {
    for (int i = 0; i < dirEntries.length; i++) {
      delete(client, new Path(absolute, dirEntries[i].getPath()), recursive);
    }
  }
  return client.removeDirectory(pathName);
}
 
Example 8
Source File: FTPFileSystem.java    From hadoop-gpu with Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method, so that we don't open a new connection when using this
 * method from within another method. Otherwise every API invocation incurs
 * the overhead of opening/closing a TCP connection.
 */
private boolean delete(FTPClient client, Path file, boolean recursive)
    throws IOException {
  Path workDir = new Path(client.printWorkingDirectory());
  Path absolute = makeAbsolute(workDir, file);
  String pathName = absolute.toUri().getPath();
  FileStatus fileStat = getFileStatus(client, absolute);
  if (!fileStat.isDir()) {
    return client.deleteFile(pathName);
  }
  FileStatus[] dirEntries = listStatus(client, absolute);
  if (dirEntries != null && dirEntries.length > 0 && !(recursive)) {
    throw new IOException("Directory: " + file + " is not empty.");
  }
  if (dirEntries != null) {
    for (int i = 0; i < dirEntries.length; i++) {
      delete(client, new Path(absolute, dirEntries[i].getPath()), recursive);
    }
  }
  return client.removeDirectory(pathName);
}
 
Example 9
Source File: FTPTransfer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteDirectory(final String remoteDirectoryName) throws IOException {
    final FTPClient client = getClient(null);
    final boolean success = client.removeDirectory(remoteDirectoryName);
    if (!success) {
        throw new IOException("Failed to remove directory " + remoteDirectoryName + " due to " + client.getReplyString());
    }
}
 
Example 10
Source File: FTPTransfer.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteDirectory(final FlowFile flowFile, final String remoteDirectoryName) throws IOException {
    final FTPClient client = getClient(flowFile);
    final boolean success = client.removeDirectory(remoteDirectoryName);
    if (!success) {
        throw new IOException("Failed to remove directory " + remoteDirectoryName + " due to " + client.getReplyString());
    }
}
 
Example 11
Source File: FTPServerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test CRUD for FTP server
 *
 * @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();
    }    
}
 
Example 12
Source File: FTPServerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test of obscure path names in the FTP server
 * 
 * RFC959 states that paths are constructed thus...
 * <string> ::= <char> | <char><string>
 * <pathname> ::= <string>
 * <char> ::= any of the 128 ASCII characters except <CR> and <LF>
 *       
 *  So we need to check how high characters and problematic are encoded     
 */
public void testPathNames() throws Exception
{
    
    logger.debug("Start testPathNames");
    
    FTPClient ftp = connectClient();

    String PATH1="testPathNames";
    
    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 for this test
        boolean success = ftp.makeDirectory(PATH1);
        assertTrue("unable to make directory:" + PATH1, success);
        
        success = ftp.changeWorkingDirectory(PATH1);
        assertTrue("unable to change to working directory:" + PATH1, success);
        
        assertTrue("with a space", ftp.makeDirectory("test space"));
        assertTrue("with exclamation", ftp.makeDirectory("space!"));
        assertTrue("with dollar", ftp.makeDirectory("space$"));
        assertTrue("with brackets", ftp.makeDirectory("space()"));
        assertTrue("with hash curley  brackets", ftp.makeDirectory("space{}"));


        //Pound sign U+00A3
        //Yen Sign U+00A5
        //Capital Omega U+03A9

        assertTrue("with pound sign", ftp.makeDirectory("pound \u00A3.world"));
        assertTrue("with yen sign", ftp.makeDirectory("yen \u00A5.world"));
        
        // Test steps that do not work
        // assertTrue("with omega", ftp.makeDirectory("omega \u03A9.world"));
        // assertTrue("with obscure ASCII chars", ftp.makeDirectory("?/.,<>"));    
    } 
    finally
    {
        // clean up tree if left over from previous run

        ftp.disconnect();
    }    


}
 
Example 13
Source File: FTPServerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test of rename case ALF-20584
 * 
  
 */
public void testRenameCase() throws Exception
{
    
    logger.debug("Start testRenameCase");
    
    FTPClient ftp = connectClient();

    String PATH1="testRenameCase";
    
    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 for this test
        boolean success = ftp.makeDirectory(PATH1);
        assertTrue("unable to make directory:" + PATH1, success);
        
        ftp.cwd(PATH1);
        
        String FILE1_CONTENT_2="That's how it is says Pooh!";
        ftp.storeFile("FileA.txt" , new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));
        
        assertTrue("unable to rename", ftp.rename("FileA.txt", "FILEA.TXT"));
    
    } 
    finally
    {
        // clean up tree if left over from previous run

        ftp.disconnect();
    }    


}