Example usage for org.apache.commons.net.ftp FTPFile isFile

List of usage examples for org.apache.commons.net.ftp FTPFile isFile

Introduction

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

Prototype

public boolean isFile() 

Source Link

Document

Determine if the file is a regular file.

Usage

From source file:com.sos.VirtualFileSystem.FTP.SOSVfsFtpBaseClass.java

/**
 * return a listing of the contents of a directory in short format on
 * the remote machine (without subdirectory)
 *
 * @param pathname on remote machine//ww w  .  j  a va  2  s .  com
 * @return a listing of the contents of a directory on the remote machine
 * @throws IOException
 *
 * @exception Exception
 * @see #dir()
 */
private Vector<String> getFilenames(final String pstrPathName, final boolean flgRecurseSubFolders) {
    String strCurrentDirectory = null;
    // TODO vecDirectoryListing = null; prfen, ob notwendig
    vecDirectoryListing = null;
    if (vecDirectoryListing == null) {
        vecDirectoryListing = new Vector<String>();
        String[] fileList = null;
        strCurrentDirectory = DoPWD();
        String lstrPathName = pstrPathName.trim();
        if (lstrPathName.length() <= 0) {
            lstrPathName = ".";
        }
        if (lstrPathName.equals(".")) {
            lstrPathName = strCurrentDirectory;
        }
        FTPFile[] objFTPFileList = null;
        try {
            objFTPFileList = Client().listFiles(lstrPathName);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        //         if (1 == 1) {
        //            try {
        //               fileList = listNames(lstrPathName);
        //               // fileList = listNames(pstrPathName);
        //            }
        //            catch (IOException e) {
        //               e.printStackTrace(System.err);
        //            }
        //         }
        // else {
        // FTPFile[] objFtpFiles = Client().listFiles(lstrPathName);
        // if (objFtpFiles != null) {
        // int i = 0;
        // for (FTPFile ftpFile : objFtpFiles) {
        // fileList[i++] = ftpFile.getName();
        // }
        // }
        // }
        if (objFTPFileList == null) {
            return vecDirectoryListing;
        }
        for (FTPFile ftpFile : objFTPFileList) {
            String strCurrentFile = ftpFile.getName();
            if (isNotHiddenFile(strCurrentFile)) {
                if (flgRecurseSubFolders == false && ftpFile.isFile()) {
                    if (strCurrentFile.startsWith(strCurrentDirectory) == false)
                        strCurrentFile = strCurrentDirectory + "/" + strCurrentFile;
                    vecDirectoryListing.add(strCurrentFile);
                } else {
                    //                  DoCD(strCurrentFile); // is this file-entry a subfolder?
                    //                  if (isNegativeCommandCompletion()) {
                    if (ftpFile.isFile()) {
                        if (strCurrentFile.startsWith(strCurrentDirectory) == false)
                            strCurrentFile = strCurrentDirectory + "/" + strCurrentFile;
                        vecDirectoryListing.add(strCurrentFile);
                    } else {
                        //                     DoCD(strCurrentDirectory);
                        if (ftpFile.isDirectory() && flgRecurseSubFolders) {
                            Vector<String> vecNames = getFilenames(strCurrentFile);
                            if (vecNames != null) {
                                vecDirectoryListing.addAll(vecNames);
                            }
                        }
                    }
                }
            }
        }
    }
    logger.debug(SOSVfs_I_126.params(strCurrentDirectory));
    if (strCurrentDirectory != null) {
        DoCD(strCurrentDirectory);
        DoPWD();
    }
    return vecDirectoryListing;
}

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * check FTPFiles to check whether they function as directories too
 * the FTPFile API seem to make directory and symbolic links incompatible
 * we want to find out if we can cd to a symbolic link
 * @param dir  the parent directory of the file to test
 * @param file the file to test//from   w w w  .ja v a 2s .c  o  m
 * @return true if it is possible to cd to this directory
 * @since ant 1.6
 */
private boolean isFunctioningAsFile(FTPClient ftp, String dir, FTPFile file) {
    if (file.isDirectory()) {
        return false;
    } else if (file.isFile()) {
        return true;
    }
    return !isFunctioningAsDirectory(ftp, dir, file);
}

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * check FTPFiles to check whether they function as directories too
 * the FTPFile API seem to make directory and symbolic links incompatible
 * we want to find out if we can cd to a symbolic link
 * @param dir  the parent directory of the file to test
 * @param file the file to test/*from w w w . j av  a  2s. c  o m*/
 * @return true if it is possible to cd to this directory
 * @since ant 1.6
 */
private boolean isFunctioningAsDirectory(FTPClient ftp, String dir, FTPFile file) {
    boolean result = false;
    String currentWorkingDir = null;
    if (file.isDirectory()) {
        return true;
    } else if (file.isFile()) {
        return false;
    }
    try {
        currentWorkingDir = ftp.printWorkingDirectory();
    } catch (IOException ioe) {
        getProject().log("could not find current working directory " + dir + " while checking a symlink",
                Project.MSG_DEBUG);
    }
    if (currentWorkingDir != null) {
        try {
            result = ftp.changeWorkingDirectory(file.getLink());
        } catch (IOException ioe) {
            getProject().log("could not cd to " + file.getLink() + " while checking a symlink",
                    Project.MSG_DEBUG);
        }
        if (result) {
            boolean comeback = false;
            try {
                comeback = ftp.changeWorkingDirectory(currentWorkingDir);
            } catch (IOException ioe) {
                getProject().log("could not cd back to " + dir + " while checking a symlink", Project.MSG_ERR);
            } finally {
                if (!comeback) {
                    throw new BuildException("could not cd back to " + dir + " while checking a symlink");
                }
            }
        }
    }
    return result;
}

From source file:nl.esciencecenter.xenon.adaptors.filesystems.ftp.FtpFileSystem.java

private PathAttributes convertAttributes(Path path, FTPFile attributes) {

    PathAttributesImplementation result = new PathAttributesImplementation();

    result.setPath(path);/*w  w w  . j ava  2  s  . c o  m*/
    result.setDirectory(attributes.isDirectory());
    result.setRegular(attributes.isFile());
    result.setOther(attributes.isUnknown());
    result.setSymbolicLink(attributes.isSymbolicLink());

    result.setLastModifiedTime(attributes.getTimestamp().getTimeInMillis());
    result.setCreationTime(attributes.getTimestamp().getTimeInMillis());
    result.setLastAccessTime(attributes.getTimestamp().getTimeInMillis());

    result.setSize(attributes.getSize());

    Set<PosixFilePermission> permission = getPermissions(attributes);

    result.setExecutable(permission.contains(PosixFilePermission.OWNER_EXECUTE));
    result.setReadable(permission.contains(PosixFilePermission.OWNER_READ));
    result.setWritable(permission.contains(PosixFilePermission.OWNER_WRITE));

    result.setPermissions(permission);

    result.setGroup(attributes.getGroup());
    result.setOwner(attributes.getUser());

    return result;
}

From source file:no.imr.sea2data.stox.InstallerUtil.java

public static Boolean retrieveReadMeFromFTP(String ftpPath, String outFile) {
    return retrieveFromFTP(ftpPath, outFile,
            (FTPFile ftpFile) -> ftpFile.isFile() && ftpFile.getName().startsWith(README));
}

From source file:org.abstracthorizon.proximity.storage.remote.CommonsNetFtpRemotePeer.java

/**
 * Construct item properties from get response.
 * //from   www .  j a v a2s . c  o  m
 * @param path the path
 * @param originatingUrlString the originating url string
 * @param remoteFile the remote file
 * 
 * @return the item properties
 * 
 * @throws MalformedURLException the malformed URL exception
 */
protected ItemProperties constructItemPropertiesFromGetResponse(String path, String originatingUrlString,
        FTPFile remoteFile) throws MalformedURLException {
    URL originatingUrl = new URL(originatingUrlString);
    ItemProperties result = new HashMapItemPropertiesImpl();
    result.setDirectoryPath(
            FilenameUtils.separatorsToUnix(FilenameUtils.getPath(FilenameUtils.getFullPath(path))));
    result.setDirectory(remoteFile.isDirectory());
    result.setFile(remoteFile.isFile());
    result.setLastModified(remoteFile.getTimestamp().getTime());
    result.setName(FilenameUtils.getName(originatingUrl.getPath()));
    if (result.isFile()) {
        result.setSize(remoteFile.getSize());
    } else {
        result.setSize(0);
    }
    result.setRemoteUrl(originatingUrl.toString());
    return result;
}

From source file:org.apache.camel.component.file.remote.FtpConsumer.java

protected boolean doPollDirectory(String absolutePath, String dirName, List<GenericFile<FTPFile>> fileList,
        int depth) {
    log.trace("doPollDirectory from absolutePath: {}, dirName: {}", absolutePath, dirName);

    depth++;/*from  w  w w.  ja v a2  s  .c om*/

    // remove trailing /
    dirName = FileUtil.stripTrailingSeparator(dirName);

    // compute dir depending on stepwise is enabled or not
    String dir;
    if (isStepwise()) {
        dir = ObjectHelper.isNotEmpty(dirName) ? dirName : absolutePath;
        operations.changeCurrentDirectory(dir);
    } else {
        dir = absolutePath;
    }

    log.trace("Polling directory: {}", dir);
    List<FTPFile> files = null;
    if (isUseList()) {
        if (isStepwise()) {
            files = operations.listFiles();
        } else {
            files = operations.listFiles(dir);
        }
    } else {
        // we cannot use the LIST command(s) so we can only poll a named file
        // so created a pseudo file with that name
        FTPFile file = new FTPFile();
        file.setType(FTPFile.FILE_TYPE);
        fileExpressionResult = evaluateFileExpression();
        if (fileExpressionResult != null) {
            file.setName(fileExpressionResult);
            files = new ArrayList<FTPFile>(1);
            files.add(file);
        }
    }

    if (files == null || files.isEmpty()) {
        // no files in this directory to poll
        log.trace("No files found in directory: {}", dir);
        return true;
    } else {
        // we found some files
        log.trace("Found {} in directory: {}", files.size(), dir);
    }

    for (FTPFile file : files) {

        if (log.isTraceEnabled()) {
            log.trace("FtpFile[name={}, dir={}, file={}]",
                    new Object[] { file.getName(), file.isDirectory(), file.isFile() });
        }

        // check if we can continue polling in files
        if (!canPollMoreFiles(fileList)) {
            return false;
        }

        if (file.isDirectory()) {
            RemoteFile<FTPFile> remote = asRemoteFile(absolutePath, file);
            if (endpoint.isRecursive() && depth < endpoint.getMaxDepth() && isValidFile(remote, true, files)) {
                // recursive scan and add the sub files and folders
                String subDirectory = file.getName();
                String path = absolutePath + "/" + subDirectory;
                boolean canPollMore = pollSubDirectory(path, subDirectory, fileList, depth);
                if (!canPollMore) {
                    return false;
                }
            }
        } else if (file.isFile()) {
            RemoteFile<FTPFile> remote = asRemoteFile(absolutePath, file);
            if (depth >= endpoint.getMinDepth() && isValidFile(remote, false, files)) {
                // matched file so add
                fileList.add(remote);
            }
        } else {
            log.debug("Ignoring unsupported remote file type: " + file);
        }
    }

    return true;
}

From source file:org.apache.flume.source.FTPSource.java

@SuppressWarnings("UnnecessaryContinue")
public void discoverElements(FTPClient ftpClient, String parentDir, String currentDir, int level)
        throws IOException {

    String dirToList = parentDir;
    if (!currentDir.equals("")) {
        dirToList += "/" + currentDir;
    }//  w w w.  jav  a 2 s  .c  om
    FTPFile[] subFiles = ftpClient.listFiles(dirToList);
    if (subFiles != null && subFiles.length > 0) {

        for (FTPFile aFile : subFiles) {
            String currentFileName = aFile.getName();
            if (currentFileName.equals(".") || currentFileName.equals("..")) {
                log.info("Skip parent directory and directory itself");
                continue;
            }

            if (aFile.isDirectory()) {
                log.info("[" + aFile.getName() + "]");
                ftpClient.changeWorkingDirectory(parentDir);
                discoverElements(ftpClient, dirToList, aFile.getName(), level + 1);
                continue;
            } else if (aFile.isFile()) { //aFile is a regular file
                ftpClient.changeWorkingDirectory(dirToList);
                existFileList.add(dirToList + "/" + aFile.getName()); //control of deleted files in server
                String fileName = aFile.getName();
                if (!(sizeFileList.containsKey(dirToList + "/" + aFile.getName()))) { //new file
                    ftpSourceCounter.incrementFilesCount();
                    InputStream inputStream = null;
                    try {
                        inputStream = ftpClient.retrieveFileStream(aFile.getName());
                        listener.fileStreamRetrieved();
                        readStream(inputStream, 0);
                        boolean success = inputStream != null && ftpClient.completePendingCommand(); //mandatory
                        if (success) {
                            sizeFileList.put(dirToList + "/" + aFile.getName(), aFile.getSize());
                            saveMap(sizeFileList);
                            ftpSourceCounter.incrementFilesProcCount();
                            log.info("discovered: " + fileName + " ," + sizeFileList.size());
                        } else {
                            handleProcessError(fileName);
                        }
                    } catch (FTPConnectionClosedException e) {
                        handleProcessError(fileName);
                        log.error("Ftp server closed connection ", e);
                        continue;
                    }

                    ftpClient.changeWorkingDirectory(dirToList);
                    continue;

                } else { //known file                        
                    long dif = aFile.getSize() - sizeFileList.get(dirToList + "/" + aFile.getName());
                    if (dif > 0) { //known and modified
                        long prevSize = sizeFileList.get(dirToList + "/" + aFile.getName());
                        InputStream inputStream = null;
                        try {
                            inputStream = ftpClient.retrieveFileStream(aFile.getName());
                            listener.fileStreamRetrieved();
                            readStream(inputStream, prevSize);

                            boolean success = inputStream != null && ftpClient.completePendingCommand(); //mandatory
                            if (success) {
                                sizeFileList.put(dirToList + "/" + aFile.getName(), aFile.getSize());
                                saveMap(sizeFileList);
                                ftpSourceCounter.incrementCountModProc();
                                log.info("modified: " + fileName + " ," + sizeFileList.size());
                            } else {
                                handleProcessError(fileName);
                            }
                        } catch (FTPConnectionClosedException e) {
                            log.error("Ftp server closed connection ", e);
                            handleProcessError(fileName);
                            continue;
                        }

                        ftpClient.changeWorkingDirectory(dirToList);
                        continue;
                    } else if (dif < 0) { //known and full modified
                        existFileList.remove(dirToList + "/" + aFile.getName()); //will be rediscovered as new file
                        saveMap(sizeFileList);
                        continue;
                    }
                    ftpClient.changeWorkingDirectory(parentDir);
                    continue;
                }
            } else if (aFile.isSymbolicLink()) {
                log.info(aFile.getName() + " is a link of " + aFile.getLink() + " access denied");
                ftpClient.changeWorkingDirectory(parentDir);
                continue;
            } else if (aFile.isUnknown()) {
                log.info(aFile.getName() + " unknown type of file");
                ftpClient.changeWorkingDirectory(parentDir);
                continue;
            } else {
                ftpClient.changeWorkingDirectory(parentDir);
                continue;
            }

        } //fin de bucle
    } //el listado no es vaco
}

From source file:org.apache.ftpserver.clienttests.ListTest.java

public void testListFilesInDir() throws Exception {

    TEST_DIR1.mkdirs();//ww w . j  a v a2s .  c o m
    TEST_FILE_IN_DIR1.createNewFile();
    TEST_DIR_IN_DIR1.mkdirs();

    FTPFile[] files = client.listFiles(TEST_DIR1.getName());

    assertEquals(2, files.length);

    FTPFile file = getFile(files, TEST_FILE_IN_DIR1.getName());
    assertEquals(TEST_FILE_IN_DIR1.getName(), file.getName());
    assertEquals(0, file.getSize());
    assertEquals("group", file.getGroup());
    assertEquals("user", file.getUser());
    assertTrue(file.isFile());
    assertFalse(file.isDirectory());

    file = getFile(files, TEST_DIR_IN_DIR1.getName());
    assertEquals(TEST_DIR_IN_DIR1.getName(), file.getName());
    assertEquals(0, file.getSize());
    assertEquals("group", file.getGroup());
    assertEquals("user", file.getUser());
    assertFalse(file.isFile());
    assertTrue(file.isDirectory());

}

From source file:org.apache.ftpserver.clienttests.ListTest.java

public void testListFile() throws Exception {

    TEST_DIR1.mkdirs();//from w  ww  .jav a  2  s  .  c  om
    TEST_FILE1.createNewFile();
    TEST_FILE2.createNewFile();

    FTPFile[] files = client.listFiles(TEST_FILE1.getName());

    assertEquals(1, files.length);

    FTPFile file = getFile(files, TEST_FILE1.getName());
    assertEquals(TEST_FILE1.getName(), file.getName());
    assertEquals(0, file.getSize());
    assertEquals("group", file.getGroup());
    assertEquals("user", file.getUser());
    assertTrue(file.isFile());
    assertFalse(file.isDirectory());

    Calendar expectedTimestamp = Calendar.getInstance();
    expectedTimestamp.setTimeInMillis(TEST_FILE1.lastModified());
    // server does not supply seconds and milliseconds
    expectedTimestamp.clear(Calendar.SECOND);
    expectedTimestamp.clear(Calendar.MILLISECOND);

    assertEquals(expectedTimestamp, file.getTimestamp());
}