Example usage for org.apache.commons.net.ftp FTPClient listFiles

List of usage examples for org.apache.commons.net.ftp FTPClient listFiles

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPClient listFiles.

Prototype

public FTPFile[] listFiles() throws IOException 

Source Link

Document

Using the default system autodetect mechanism, obtain a list of file information for the current working directory.

Usage

From source file:org.amanzi.neo.geoptima.loader.ui.widgets.impl.FtpTreeViewer.java

public void initialize(final FTPClient client) {
    setContentProvider(new FtpContentProvider(client));
    setLabelProvider(new FtpLabelProvider());
    try {/*from   ww  w.  j  a v  a 2  s.  co  m*/
        setInput(client.listFiles());
    } catch (IOException e) {
        // TODO KV: handle exception
        e.printStackTrace();
    }
}

From source file:org.apache.sqoop.connector.mainframe.MainframeFTPClientUtils.java

public static List<String> listSequentialDatasets(String pdsName, TransferableContext context,
        LinkConfiguration linkConfiguration) throws IOException {
    List<String> datasets = new ArrayList<String>();
    FTPClient ftp = null;
    try {/*from   www  . j  a  v  a2s . c  o m*/
        ftp = getFTPConnection(context, linkConfiguration);
        if (ftp != null) {
            setWorkingDirectory(context, ftp, pdsName);
            FTPFile[] ftpFiles = ftp.listFiles();
            for (FTPFile f : ftpFiles) {
                if (f.getType() == FTPFile.FILE_TYPE) {
                    datasets.add(f.getName());
                }
            }
        }
    } catch (IOException ioe) {
        throw new IOException("Could not list datasets from " + pdsName + ":" + ioe.toString());
    } finally {
        if (ftp != null) {
            closeFTPConnection(ftp);
        }
    }
    return datasets;
}

From source file:org.apache.sqoop.util.MainframeFTPClientUtils.java

public static List<String> listSequentialDatasets(String pdsName, Configuration conf) throws IOException {
    List<String> datasets = new ArrayList<String>();
    String dsName = pdsName;//  www. jav  a  2s . co  m
    String fileName = "";
    MainframeDatasetPath p = null;
    try {
        p = new MainframeDatasetPath(dsName, conf);
    } catch (Exception e) {
        LOG.error(e.getMessage());
        LOG.error("MainframeDatasetPath helper class incorrectly initialised");
        e.printStackTrace();
    }
    String dsType = conf.get(MainframeConfiguration.MAINFRAME_INPUT_DATASET_TYPE);
    boolean isTape = Boolean.parseBoolean(conf.get(MainframeConfiguration.MAINFRAME_INPUT_DATASET_TAPE));
    boolean isSequentialDs = false;
    boolean isGDG = false;
    if (dsType != null && p != null) {
        isSequentialDs = p.getMainframeDatasetType().toString()
                .equals(MainframeConfiguration.MAINFRAME_INPUT_DATASET_TYPE_SEQUENTIAL);
        isGDG = p.getMainframeDatasetType().toString()
                .equals(MainframeConfiguration.MAINFRAME_INPUT_DATASET_TYPE_GDG);
        pdsName = p.getMainframeDatasetFolder();
        fileName = p.getMainframeDatasetFileName();
    }
    FTPClient ftp = null;
    try {
        ftp = getFTPConnection(conf);
        if (ftp != null) {
            ftp.changeWorkingDirectory("'" + pdsName + "'");
            FTPFile[] ftpFiles = null;
            if (isTape) {
                FTPListParseEngine parser = ftp.initiateListParsing(
                        MainframeConfiguration.MAINFRAME_FTP_FILE_ENTRY_PARSER_CLASSNAME, "");
                List<FTPFile> listing = new ArrayList<FTPFile>();
                while (parser.hasNext()) {
                    FTPFile[] files = parser.getNext(25);
                    for (FTPFile file : files) {
                        if (file != null) {
                            listing.add(file);
                            LOG.info(String.format("Name: %s Type: %s", file.getName(), file.getType()));
                        }
                        // skip nulls returned from parser
                    }
                    ftpFiles = new FTPFile[listing.size()];
                    for (int i = 0; i < listing.size(); i++) {
                        ftpFiles[i] = listing.get(i);
                    }
                    LOG.info("Files returned from mainframe parser:-");
                    for (FTPFile f : ftpFiles) {
                        LOG.info(String.format("Name: %s, Type: %s", f.getName(), f.getType()));
                    }
                }
            } else {
                ftpFiles = ftp.listFiles();
            }
            if (!isGDG) {
                for (FTPFile f : ftpFiles) {
                    LOG.info(String.format("Name: %s Type: %s", f.getName(), f.getType()));
                    if (f.getType() == FTPFile.FILE_TYPE) {
                        // only add datasets if default behaviour of partitioned data sets
                        // or if it is a sequential data set, only add if the file name matches exactly
                        if (!isSequentialDs
                                || isSequentialDs && f.getName().equals(fileName) && !fileName.equals("")) {
                            datasets.add(f.getName());
                        }
                    }
                }
            } else {
                LOG.info("GDG branch. File list:-");
                for (FTPFile f : ftpFiles) {
                    LOG.info(String.format("Name: %s Type: %s", f.getName(), f.getType()));
                }
                if (ftpFiles.length > 0 && ftpFiles[ftpFiles.length - 1].getType() == FTPFile.FILE_TYPE) {
                    // for GDG - add the last file in the collection
                    datasets.add(ftpFiles[ftpFiles.length - 1].getName());
                }
            }
        }
    } catch (IOException ioe) {
        throw new IOException("Could not list datasets from " + pdsName + ":" + ioe.toString());
    } finally {
        if (ftp != null) {
            closeFTPConnection(ftp);
        }
    }
    return datasets;
}

From source file:org.apache.tools.ant.taskdefs.optional.net.FTPTaskMirrorImpl.java

/**
 *  find a suitable name for local and remote temporary file
 *//*from  w ww .  j  a v  a2s  .co m*/
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, task.getLocation());
        }
        if (!found) {
            localFile.deleteOnExit();
            return localFile;
        }
    }
    return null;
}

From source file:org.jboss.ejb3.examples.ch06.filetransfer.FileTransferBean.java

@Override
public String pwd() {
    // Get the client
    final FTPClient client = this.getClient();

    // Exec pwd//from   w  w w  .  j a v  a  2  s  .  com
    try {
        final FTPFile[] files = client.listFiles();
        for (final FTPFile file : files) {
            log.info(file.toString());
        }

        // Exec pwd
        String dir = client.printWorkingDirectory();
        String separator = File.separator;

        if ("\\".equals(separator)) {
            // reformat to use for windows
            if (dir.startsWith("/")) {
                dir = dir.substring(1);
            }
            dir = dir.replaceAll("/", "\\" + separator);
        }

        return dir;

    } catch (final IOException ioe) {
        throw new FileTransferException("Could not print working directory", ioe);
    }
}

From source file:org.jevis.commons.driver.DataSourceHelper.java

public static List<String> getFTPMatchedFileNames(FTPClient fc, DateTime lastReadout, String filePath) {
    filePath = filePath.replace("\\", "/");
    String[] pathStream = getPathTokens(filePath);

    String startPath = "";
    if (filePath.startsWith("/")) {
        startPath = "/";
    }/*w  w w . ja va2  s  .  c  om*/

    List<String> folderPathes = getMatchingPathes(startPath, pathStream, new ArrayList<String>(), fc,
            lastReadout, new DateTimeFormatterBuilder());
    //        System.out.println("foldersize,"+folderPathes.size());
    List<String> fileNames = new ArrayList<String>();

    if (folderPathes.isEmpty()) {
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                "Cant find suitable folder on the device");
        return fileNames;
    }

    //        String fileName = null;
    String fileNameScheme = pathStream[pathStream.length - 1];
    String currentfolder = null;
    try {
        for (String folder : folderPathes) {
            //                fc.changeWorkingDirectory(folder);
            //                System.out.println("currentFolder,"+folder);
            currentfolder = folder;
            //                for (FTPFile file : fc.listFiles(folder)) {
            //                    System.out.println(file.getName());
            //                }
            fc.changeWorkingDirectory(folder);
            for (FTPFile file : fc.listFiles()) {
                //                    org.apache.log4j.Logger.getLogger(Launcher.class.getName()).log(org.apache.log4j.Level.ALL, "CurrentFileName: " + fileName);
                //                    fileName = removeFoler(fileName, folder);
                if (file.getTimestamp().compareTo(lastReadout.toGregorianCalendar()) < 0) {
                    continue;
                }
                boolean match = false;
                System.out.println(file.getName());
                if (DataSourceHelper.containsTokens(fileNameScheme)) {
                    boolean matchDate = matchDateString(file.getName(), fileNameScheme);
                    DateTime folderTime = getFileTime(folder + file.getName(), pathStream);
                    boolean isLater = folderTime.isAfter(lastReadout);
                    if (matchDate && isLater) {
                        match = true;
                    }
                } else {
                    Pattern p = Pattern.compile(fileNameScheme);
                    Matcher m = p.matcher(file.getName());
                    match = m.matches();
                }
                if (match) {
                    fileNames.add(folder + file.getName());
                }
            }
        }
    } catch (IOException ex) {
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                ex.getMessage());
    } catch (Exception ex) {
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                "Error while searching a matching file");
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                "Folder: " + currentfolder);
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                "FileName: " + fileNameScheme);
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                ex.getMessage());
    }
    if (folderPathes.isEmpty()) {
        org.apache.log4j.Logger.getLogger(DataSourceHelper.class).log(org.apache.log4j.Level.ERROR,
                "Cant find suitable files on the device");
    }
    //        System.out.println("filenamesize"+fileNames.size());
    return fileNames;
}

From source file:org.openconcerto.ftp.FTPUtils.java

static public final void saveR(FTPClient ftp, File local) throws IOException {
    local.mkdirs();/*w ww.j a v  a  2s  .  com*/
    for (FTPFile child : ftp.listFiles()) {
        final String childName = child.getName();
        if (childName.indexOf('.') != 0) {
            if (child.isDirectory()) {
                ftp.changeWorkingDirectory(childName);
                saveR(ftp, new File(local, childName));
                ftp.changeToParentDirectory();
            } else {
                final OutputStream outs = new FileOutputStream(new File(local, childName));
                ftp.retrieveFile(childName, outs);
                outs.close();
            }
        }
    }
}

From source file:org.openconcerto.ftp.FTPUtils.java

static public final void recurse(FTPClient ftp, ExnClosure<FTPFile, ?> c, RecursionType type)
        throws IOException {
    for (FTPFile child : ftp.listFiles()) {
        if (child.getName().indexOf('.') != 0) {
            if (type == RecursionType.BREADTH_FIRST)
                c.executeCheckedWithExn(child, IOException.class);
            if (child.isDirectory()) {
                ftp.changeWorkingDirectory(child.getName());
                recurse(ftp, c, type);//w  w w.j  a  v  a 2 s  . c o  m
                ftp.changeToParentDirectory();
            }
            if (type == RecursionType.DEPTH_FIRST)
                c.executeCheckedWithExn(child, IOException.class);
        }
    }
}

From source file:org.oss.digitalforms.MobileFormsImpl.java

private void ftpValidations(String ftpHost, String user, String password) throws Exception {
    FTPClient ftp = new FTPClient();
    ftp.connect(ftpHost);/*from   w  w w  .  j  a v  a  2s.  c  o  m*/
    int reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        throw new Exception("Exception in connecting to FTP Server");
    }
    ftp.login(user, password);
    ftp.listFiles();
    ftp.disconnect();
}

From source file:org.schedoscope.export.ftp.FtpExportCSVMRTest.java

private int getFileCount() throws IOException {

    FTPClient ftp = new FTPClient();
    ftp.connect("localhost", 2221);
    ftp.login(EmbeddedFtpSftpServer.FTP_USER_FOR_TESTING, EmbeddedFtpSftpServer.FTP_PASS_FOR_TESTING);
    FTPFile[] files = ftp.listFiles();

    int fileCounter = 0;
    for (FTPFile f : files) {
        if (f.getName().contains(filePrefix)) {
            fileCounter += 1;//w  w  w.j ava2  s. co  m
        }
    }
    return fileCounter;
}