All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.xbib.groovy.ftp.FTP Maven / Gradle / Ivy

There is a newer version: 2.6.0
Show newest version
package org.xbib.groovy.ftp;

import groovy.lang.Closure;

import java.net.URI;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

/**
 */
public class FTP {

    private final String url;

    private final Map env;

    private FTP(String url, Map env) {
        this.url = url;
        this.env = env;
    }

    public static FTP newInstance() {
        return newInstance("ftp://localhost:21");
    }

    public static FTP newInstance(Map env) {
        return newInstance("ftp://localhost:21", env);
    }

    public static FTP newInstance(String url) {
        return newInstance(url, null);
    }

    public static FTP newInstance(String url, Map env) {
        return new FTP(url, env);
    }

    public Boolean exists(String path) throws Exception {
        return performWithContext(ctx -> Files.exists(ctx.fileSystem.getPath(path)));
    }

    public void each(String path, Closure closure) throws Exception {
        WithContext action = ctx -> {
            try (DirectoryStream stream = Files.newDirectoryStream(ctx.fileSystem.getPath(path))) {
                stream.forEach(closure::call);
            }
            return null;
        };
        performWithContext(action);
    }

    public void eachFilter(String path, DirectoryStream.Filter filter, Closure closure) throws Exception {
        WithContext action = ctx -> {
            try (DirectoryStream stream = Files.newDirectoryStream(ctx.fileSystem.getPath(path), filter)) {
                stream.forEach(closure::call);
            }
            return null;
        };
        performWithContext(action);
    }

    private  T performWithContext(WithContext action) throws Exception {
        FTPContext ctx = null;
        try {
            if (url != null) {
                ctx = new FTPContext(URI.create(url), env);
                return action.perform(ctx);
            } else {
                return null;
            }
        } finally {
            if (ctx != null) {
                ctx.close();
            }
        }
    }
}