// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

public class FtpRenamer {
    public static void rename(String server, String un, String pw, String dir, List<FileHandler> actions) throws IOException {
        FTPClient cli = new FTPClient();
        cli.connect(server);
        cli.login(un,  pw);
        cli.changeWorkingDirectory(dir);
        for(FTPFile f : cli.listFiles()) {
            for(FileHandler action: actions) {
                if(action.match(f)) {
                    action.process(f, cli);
                }
            }
        }
        cli.logout();
    }
    public static void main(String[] args) throws IOException {
        List<FileHandler> actions = new ArrayList<FileHandler>();
        actions.add(new PrintAllFilenames());
        actions.add(new RenameFilesWithPrefix("z", "zzz/")); // <---- separator must be specified at end of toDir value
        rename("myserver", "myusername", "mypassword", "somedir", actions);
    }
}

interface FileHandler {
    public boolean match(FTPFile f);
    public void process(FTPFile f, FTPClient cli) throws IOException;
}

class PrintAllFilenames implements FileHandler {
    public boolean match(FTPFile f) {
        return true;
    }
    public void process(FTPFile f, FTPClient cli) {
        System.out.println(f.getName());
    }
}

class RenameFilesWithPrefix implements FileHandler {
    private String prefix;
    private String toDir;
    public RenameFilesWithPrefix(String prefix, String toDir) {
        this.prefix = prefix;
        this.toDir = toDir;
    }
    public boolean match(FTPFile f) {
        return f.getName().startsWith(prefix);
    }
    public void process(FTPFile f, FTPClient cli) throws IOException {
        cli.rename(f.getName(), toDir + f.getName());
    }
}
