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

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

Introduction

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

Prototype

public boolean isSymbolicLink() 

Source Link

Document

Determine if the file is a symbolic link.

Usage

From source file:at.beris.virtualfile.client.ftp.FtpFileTranslator.java

public static void fillModel(FileModel model, FTPFile ftpFile, FtpClient client) throws IOException {
    String physicalRootPath = client.getPhysicalRootPath();
    String parentPath = model.getParent() != null ? model.getParent().getUrl().getPath() : "";

    if (!"".equals(physicalRootPath)) {
        if (parentPath.length() >= physicalRootPath.length()
                && parentPath.substring(0, physicalRootPath.length()).equals(physicalRootPath))
            parentPath = "/" + parentPath.substring(physicalRootPath.length());
    }/*from  ww  w  .java2 s . c  o m*/

    if (ftpFile.isSymbolicLink()) {
        String linkPath = ftpFile.getLink() + (ftpFile.getLink().endsWith("/") ? "" : "/");

        if (!"".equals(physicalRootPath)) {
            if (linkPath.length() >= physicalRootPath.length()
                    && linkPath.substring(0, physicalRootPath.length()).equals(physicalRootPath))
                linkPath = "/" + linkPath.substring(physicalRootPath.length());
        }
        String filePath = parentPath + linkPath;
        URL linkTargetUrl = UrlUtils
                .normalizeUrl(UrlUtils.newUrlReplacePath(model.getParent().getUrl(), filePath));
        model.setLinkTarget(linkTargetUrl);
    }

    model.setFileExists(true);
    model.setSize(ftpFile.getSize());
    model.setCreationTime(null);
    model.setLastModifiedTime(FileTime.fromMillis(ftpFile.getTimestamp().getTime().getTime()));
    model.setLastAccessTime(null);
    model.setAttributes(createAttributes(ftpFile));
    model.setOwner(new UnixUserPrincipal(ftpFile.getUser(), ftpFile.getGroup()));
    model.setGroup(new UnixGroupPrincipal(ftpFile.getGroup()));
    model.setDirectory(ftpFile.isDirectory());
    model.setSymbolicLink(ftpFile.isSymbolicLink());
}

From source file:at.beris.virtualfile.client.ftp.FtpClient.java

public String getPhysicalRootPath() throws IOException {
    if (physicalRootPath == null) {
        physicalRootPath = executionHandler(new Callable<String>() {
            @Override//from  ww  w.  ja v a2  s . co m
            public String call() throws Exception {
                ftpClient.changeWorkingDirectory("/");
                for (FTPFile ftpFile : ftpClient.listFiles()) {
                    if (ftpFile.isSymbolicLink() && ".".equals(ftpFile.getLink())) {
                        return "/" + ftpFile.getName() + "/";
                    }
                }
                return "";
            }
        });
    }
    return physicalRootPath;
}

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

private List<FileInfo> getListing(final String path, final int depth, final int maxResults) throws IOException {
    final List<FileInfo> listing = new ArrayList<>();
    if (maxResults < 1) {
        return listing;
    }/*w w w.  j  a  v  a2s .c o  m*/

    if (depth >= 100) {
        logger.warn(this + " had to stop recursively searching directories at a recursive depth of " + depth
                + " to avoid memory issues");
        return listing;
    }

    final boolean ignoreDottedFiles = ctx.getProperty(FileTransferV2.IGNORE_DOTTED_FILES).asBoolean();
    final boolean recurse = ctx.getProperty(FileTransferV2.RECURSIVE_SEARCH).asBoolean();
    final String fileFilterRegex = ctx.getProperty(FileTransferV2.FILE_FILTER_REGEX).getValue();
    final Pattern pattern = (fileFilterRegex == null) ? null : Pattern.compile(fileFilterRegex);
    final String pathFilterRegex = ctx.getProperty(FileTransferV2.PATH_FILTER_REGEX).getValue();
    final Pattern pathPattern = (!recurse || pathFilterRegex == null) ? null : Pattern.compile(pathFilterRegex);
    final String remotePath = ctx.getProperty(FileTransferV2.REMOTE_PATH).evaluateAttributeExpressions()
            .getValue();

    // check if this directory path matches the PATH_FILTER_REGEX
    boolean pathFilterMatches = true;
    if (pathPattern != null) {
        Path reldir = path == null ? Paths.get(".") : Paths.get(path);
        if (remotePath != null) {
            reldir = Paths.get(remotePath).relativize(reldir);
        }
        if (reldir != null && !reldir.toString().isEmpty()) {
            if (!pathPattern.matcher(reldir.toString().replace("\\", "/")).matches()) {
                pathFilterMatches = false;
            }
        }
    }

    final FTPClient client = getClient(null);

    int count = 0;
    final FTPFile[] files;

    if (path == null || path.trim().isEmpty()) {
        files = client.listFiles(".");
    } else {
        files = client.listFiles(path);
    }
    if (files.length == 0 && path != null && !path.trim().isEmpty()) {
        // throw exception if directory doesn't exist
        final boolean cdSuccessful = setWorkingDirectory(path);
        if (!cdSuccessful) {
            throw new IOException("Cannot list files for non-existent directory " + path);
        }
    }

    for (final FTPFile file : files) {
        final String filename = file.getName();
        if (filename.equals(".") || filename.equals("..")) {
            continue;
        }

        if (ignoreDottedFiles && filename.startsWith(".")) {
            continue;
        }

        final File newFullPath = new File(path, filename);
        final String newFullForwardPath = newFullPath.getPath().replace("\\", "/");

        if (recurse && file.isDirectory()) {
            try {
                listing.addAll(getListing(newFullForwardPath, depth + 1, maxResults - count));
            } catch (final IOException e) {
                logger.error(
                        "Unable to get listing from " + newFullForwardPath + "; skipping this subdirectory");
            }
        }

        // if is not a directory and is not a link and it matches
        // FILE_FILTER_REGEX - then let's add it
        if (!file.isDirectory() && !file.isSymbolicLink() && pathFilterMatches) {
            if (pattern == null || pattern.matcher(filename).matches()) {
                listing.add(newFileInfo(file, path));
                count++;
            }
        }

        if (count >= maxResults) {
            break;
        }
    }

    return listing;
}

From source file:net.sf.jfilesync.plugins.net.items.TCommonsFTP_plugin.java

protected TFileProperties extractFileProperties(FTPFile file, FTPFile[] filesInDir) throws IOException {
    TFileProperties prop = new TFileProperties();

    prop.setFileName(file.getName());//from w ww.  j  av a2  s . com

    final String cwd = ftpClient.printWorkingDirectory();
    String fname = null;
    if (cwd.endsWith("/")) {
        fname = cwd + file.getName();
    } else {
        fname = cwd + "/" + file.getName();
    }
    prop.setAbsoluteFileName(fname);

    if (file.getName().startsWith(".")) {
        prop.setHiddenFlag(true);
    }

    // There is a little problem with ftp.getSize(), because it's sometimes
    // 0
    prop.setFileSize(new BigInteger(Long.toString(file.getSize())));
    // System.out.println(file.getName() + " , " + file.getTimestamp());
    prop.setFileModTime(file.getTimestamp().getTimeInMillis());
    // System.out.println("file: " + fname);
    // System.out.println("isDirectory: " + file.isDirectory());
    prop.setDirectoryFlag(file.isDirectory());
    prop.setLinkFlag(file.isSymbolicLink());

    int permissions = 0;

    permissions |= file.isDirectory() ? FilePermissions.S_IFDIR : 0;
    permissions |= file.isSymbolicLink() ? FilePermissions.S_IFLNK : 0;

    permissions |= file.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION) ? FilePermissions.S_IRUSR
            : 0;
    permissions |= file.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION) ? FilePermissions.S_IWUSR
            : 0;
    permissions |= file.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION) ? FilePermissions.S_IXUSR
            : 0;
    permissions |= file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION) ? FilePermissions.S_IRGRP
            : 0;
    permissions |= file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION) ? FilePermissions.S_IWGRP
            : 0;
    permissions |= file.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)
            ? FilePermissions.S_IXGRP
            : 0;
    permissions |= file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION) ? FilePermissions.S_IROTH
            : 0;
    permissions |= file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION) ? FilePermissions.S_IWOTH
            : 0;
    permissions |= file.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)
            ? FilePermissions.S_IXOTH
            : 0;

    final TFileAttributes attr = new TFileAttributes();
    attr.setPermissions(permissions);
    prop.setAttributes(attr);

    /*
     * what needs to be done is implement caching of directories which have
     * to be listed for link detection implement recursive link detection
     * for links to links SaHu July 2006
     */

    /*
     * if( file.isSymbolicLink() ) { System.out.println("link target : " +
     * file.getLink()); }
     */

    // if( file.isSymbolicLink() ) {
    // // check if link points to dir
    // final String linkTarget = file.getLink();
    // final String linkTargetBaseName =
    // getPathControl().basename(linkTarget);
    // //System.out.println("link target basename: " + linkTargetBaseName);
    // if( linkTarget != null ) {
    // String linkContaingPath =
    // getPathControl().getPathLevelUp(linkTarget);
    // FTPFile[] targetFiles = null;
    // if( linkContaingPath.equals("") || linkContaingPath.equals(cwd) ) {
    // targetFiles = filesInDir;
    // } else {
    // //System.out.println("check dir : " + linkContaingPath);
    // targetFiles = ftpClient.listFiles(linkContaingPath);
    // }
    //
    //
    // if( targetFiles != null ) {
    // for(int i=0; i<targetFiles.length; i++) {
    // //System.out.println("> " + targetFiles[i].getName());
    // if( targetFiles[i].getName().equals(linkTargetBaseName) ) {
    // if( targetFiles[i].isDirectory() ) {
    // prop.setDirectoryFlag(true);
    // }
    // break;
    // }
    // }
    // }
    // }
    // }

    if (file.isSymbolicLink()) {
        final String linkTarget = file.getLink();
        boolean result = ftpClient.changeWorkingDirectory(linkTarget);
        if (result) {
            prop.setDirectoryFlag(true);
        }
        ftpClient.changeWorkingDirectory(cwd);
    }

    return prop;
}

From source file:fr.ibp.nifi.processors.IBPFTPTransfer.java

private List<FileInfo> getListing(final String path, final int depth, final int maxResults,
        final Integer maxDepth) throws IOException {

    final List<FileInfo> listing = new ArrayList<>();
    if (maxResults < 1) {
        return listing;
    }/*  w  ww .j  ava  2 s. c om*/

    if (depth >= 100) {
        logger.warn(this + " had to stop recursively searching directories at a recursive depth of " + depth
                + " to avoid memory issues");
        return listing;
    }

    final boolean ignoreDottedFiles = ctx.getProperty(FileTransfer.IGNORE_DOTTED_FILES).asBoolean();
    final boolean recurse = ctx.getProperty(FileTransfer.RECURSIVE_SEARCH).asBoolean();
    final String fileFilterRegex = ctx.getProperty(FileTransfer.FILE_FILTER_REGEX).getValue();
    final Pattern pattern = (fileFilterRegex == null) ? null : Pattern.compile(fileFilterRegex);
    final String pathFilterRegex = ctx.getProperty(FileTransfer.PATH_FILTER_REGEX).getValue();
    final Pattern pathPattern = (!recurse || pathFilterRegex == null) ? null : Pattern.compile(pathFilterRegex);
    final String remotePath = ctx.getProperty(FileTransfer.REMOTE_PATH).evaluateAttributeExpressions()
            .getValue();

    logger.info(String.format("path : %s", path));
    logger.info(String.format("pathPattern : %s", pathPattern));

    // check if this directory path matches the PATH_FILTER_REGEX
    boolean pathFilterMatches = true;
    if (pathPattern != null) {
        Path reldir = path == null ? Paths.get(".") : Paths.get(path);
        if (remotePath != null) {
            reldir = Paths.get(remotePath).relativize(reldir);
        }
        if (reldir != null && !reldir.toString().isEmpty()) {
            if (!pathPattern.matcher(reldir.toString().replace("\\", "/")).matches()) {
                pathFilterMatches = false;
            }
        }
    }

    logger.info(String.format("pathFilterMatches : %s", pathFilterMatches));

    final FTPClient client = getClient(null);

    int count = 0;
    final FTPFile[] files;

    if (path == null || path.trim().isEmpty()) {
        files = client.listFiles(".");
    } else {
        files = client.listFiles(path);
    }
    if (files.length == 0 && path != null && !path.trim().isEmpty()) {
        // throw exception if directory doesn't exist
        final boolean cdSuccessful = setWorkingDirectory(path);
        if (!cdSuccessful) {
            throw new IOException("Cannot list files for non-existent directory " + path);
        }
    }

    for (final FTPFile file : files) {
        final String filename = file.getName();
        if (filename.equals(".") || filename.equals("..")) {
            continue;
        }

        if (ignoreDottedFiles && filename.startsWith(".")) {
            continue;
        }

        final File newFullPath = new File(path, filename);
        final String newFullForwardPath = newFullPath.getPath().replace("\\", "/");

        if (file.isDirectory()) {
            logger.info("PATH: {} ", new Object[] { newFullForwardPath });
            // Repertoire
            if (maxDepth != null) {
                // Si la profondeur de recherche est dfinieoct@ve12
                int level = maxDepth.intValue() - 1;
                if (depth == level) {
                    logger.info("depth == level");
                    boolean matches = true;
                    if (pathPattern != null) {
                        Path reldir = path == null ? Paths.get(".") : Paths.get(newFullForwardPath);
                        if (remotePath != null) {
                            reldir = Paths.get(remotePath).relativize(reldir);
                        }
                        if (reldir != null && !reldir.toString().isEmpty()) {
                            if (!pathPattern.matcher(reldir.toString().replace("\\", "/")).matches()) {
                                matches = false;
                            }
                        }
                    }
                    if (pathPattern == null || matches) {
                        try {
                            logger.info("going into depth depth:{} and maxDepth: {} ",
                                    new Object[] { depth, maxDepth });
                            listing.addAll(
                                    getListing(newFullForwardPath, depth + 1, maxResults - count, maxDepth));
                        } catch (final IOException e) {
                            logger.error("Unable to get listing from " + newFullForwardPath
                                    + "; skipping this subdirectory");
                            throw e;
                        }
                    }
                } else if (depth < level) {
                    logger.info("depth < level");
                    try {
                        logger.info("going into depth depth:{} and maxDepth: {} ",
                                new Object[] { depth, maxDepth });
                        listing.addAll(getListing(newFullForwardPath, depth + 1, maxResults - count, maxDepth));
                    } catch (final IOException e) {
                        logger.error("Unable to get listing from " + newFullForwardPath
                                + "; skipping this subdirectory");
                        throw e;
                    }
                }
            } else if (recurse) {
                logger.info("MAxDepth  null and recurse = true");
                try {
                    logger.info("Recurse mode depth depth:{}", new Object[] { depth });
                    listing.addAll(getListing(newFullForwardPath, depth + 1, maxResults - count, maxDepth));
                } catch (final IOException e) {
                    logger.error("Unable to get listing from " + newFullForwardPath
                            + "; skipping this subdirectory");
                    throw e;
                }
            }

        }

        /*
         * if ((file.isDirectory() && pathFilterMatches && maxDepth!=null &&
         * depth<=maxDepth)) { try { logger.info(
         * "going into depth depth:{} and maxDepth: {} ",new
         * Object[]{depth,maxDepth});
         * listing.addAll(getListing(newFullForwardPath, depth + 1,
         * maxResults - count, maxDepth)); } catch (final IOException e) {
         * logger.error("Unable to get listing from " + newFullForwardPath +
         * "; skipping this subdirectory"); throw e; } }else{ if ((recurse
         * && file.isDirectory()) ) { try { logger.info(
         * "Recurse mode depth depth:{}",new Object[]{depth});
         * listing.addAll(getListing(newFullForwardPath, depth + 1,
         * maxResults - count, maxDepth)); } catch (final IOException e) {
         * logger.error("Unable to get listing from " + newFullForwardPath +
         * "; skipping this subdirectory"); throw e; } } }
         */

        // if is not a directory and is not a link and it matches
        // FILE_FILTER_REGEX - then let's add it
        if (!file.isDirectory() && !file.isSymbolicLink() && pathFilterMatches) {
            if (pattern == null || pattern.matcher(filename).matches()) {
                logger.info(String.format("Ajout du fichier %s/%s", path, file.getName()));
                listing.add(newFileInfo(file, path));
                count++;
                logger.info(String.format("Nb fichiers retenus %s", count));
            }
        }

        if (count >= maxResults) {
            break;
        }
    }

    return listing;
}

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);//from w  w w  . jav a2s .  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: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;
    }//from  www.j  av a 2s.  co m
    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.nifi.processors.standard.util.FTPTransfer.java

private List<FileInfo> getListing(final String path, final int depth, final int maxResults) throws IOException {
    final List<FileInfo> listing = new ArrayList<>();
    if (maxResults < 1) {
        return listing;
    }/* ww  w.j  a v a2 s.c  om*/

    if (depth >= 100) {
        logger.warn(this + " had to stop recursively searching directories at a recursive depth of " + depth
                + " to avoid memory issues");
        return listing;
    }

    final boolean ignoreDottedFiles = ctx.getProperty(FileTransfer.IGNORE_DOTTED_FILES).asBoolean();
    final boolean recurse = ctx.getProperty(FileTransfer.RECURSIVE_SEARCH).asBoolean();
    final String fileFilterRegex = ctx.getProperty(FileTransfer.FILE_FILTER_REGEX).getValue();
    final Pattern pattern = (fileFilterRegex == null) ? null : Pattern.compile(fileFilterRegex);
    final String pathFilterRegex = ctx.getProperty(FileTransfer.PATH_FILTER_REGEX).getValue();
    final Pattern pathPattern = (!recurse || pathFilterRegex == null) ? null : Pattern.compile(pathFilterRegex);
    final String remotePath = ctx.getProperty(FileTransfer.REMOTE_PATH).evaluateAttributeExpressions()
            .getValue();

    // check if this directory path matches the PATH_FILTER_REGEX
    boolean pathFilterMatches = true;
    if (pathPattern != null) {
        Path reldir = path == null ? Paths.get(".") : Paths.get(path);
        if (remotePath != null) {
            reldir = Paths.get(remotePath).relativize(reldir);
        }
        if (reldir != null && !reldir.toString().isEmpty()) {
            if (!pathPattern.matcher(reldir.toString().replace("\\", "/")).matches()) {
                pathFilterMatches = false;
            }
        }
    }

    final FTPClient client = getClient(null);

    int count = 0;
    final FTPFile[] files;

    if (path == null || path.trim().isEmpty()) {
        files = client.listFiles(".");
    } else {
        files = client.listFiles(path);
    }
    if (files.length == 0 && path != null && !path.trim().isEmpty()) {
        // throw exception if directory doesn't exist
        final boolean cdSuccessful = setWorkingDirectory(path);
        if (!cdSuccessful) {
            throw new IOException("Cannot list files for non-existent directory " + path);
        }
    }

    for (final FTPFile file : files) {
        final String filename = file.getName();
        if (filename.equals(".") || filename.equals("..")) {
            continue;
        }

        if (ignoreDottedFiles && filename.startsWith(".")) {
            continue;
        }

        final File newFullPath = new File(path, filename);
        final String newFullForwardPath = newFullPath.getPath().replace("\\", "/");

        if (recurse && file.isDirectory()) {
            try {
                listing.addAll(getListing(newFullForwardPath, depth + 1, maxResults - count));
            } catch (final IOException e) {
                logger.error(
                        "Unable to get listing from " + newFullForwardPath + "; skipping this subdirectory");
            }
        }

        // if is not a directory and is not a link and it matches
        // FILE_FILTER_REGEX - then let's add it
        if (!file.isDirectory() && !file.isSymbolicLink() && pathFilterMatches) {
            if (pattern == null || pattern.matcher(filename).matches()) {
                listing.add(newFileInfo(file, path));
                count++;
            }
        }

        if (count >= maxResults) {
            break;
        }
    }

    return listing;
}

From source file:org.ikasan.connector.ftp.net.FileTransferProtocolClient.java

/**
 * Constructing a <code>ClientListEntry</code> object from an
 * <code>FTPFile</code> object. This is a direct map with some formatting
 * changes.//from  ww  w .j  a  va2 s.c om
 * 
 * @param ftpFile The <code>FTPFile</code> to map to a
 *            <code>ClientListEntry</code>
 * @param fileUri The URI of the underlying file for the particular
 *            <code>FTPFile</code>
 * @return ClientListEntry
 */
private ClientListEntry convertFTPFileToClientListEntry(FTPFile ftpFile, URI fileUri, String currentDir) {
    ClientListEntry clientListEntry = new ClientListEntry();
    clientListEntry.setUri(fileUri);
    clientListEntry.setName(ftpFile.getName());
    clientListEntry.setFullPath(currentDir + System.getProperty("file.separator") + ftpFile.getName());

    clientListEntry.setClientId(null);
    // Can't distinguish between Last Accessed and Last Modified
    clientListEntry.setDtLastAccessed(ftpFile.getTimestamp().getTime());
    clientListEntry.setDtLastModified(ftpFile.getTimestamp().getTime());
    clientListEntry.setSize(ftpFile.getSize());
    clientListEntry.isDirectory(ftpFile.isDirectory());
    clientListEntry.isLink(ftpFile.isSymbolicLink());
    clientListEntry.setLongFilename(ftpFile.getRawListing());
    clientListEntry.setAtime(ftpFile.getTimestamp().getTime().getTime());
    clientListEntry.setMtime(ftpFile.getTimestamp().getTime().getTime());
    clientListEntry.setAtimeString(ftpFile.getTimestamp().toString());
    clientListEntry.setMtimeString(ftpFile.getTimestamp().toString());
    // clientListEntry.setFlags();
    clientListEntry.setGid(ftpFile.getGroup());
    clientListEntry.setUid(ftpFile.getUser());
    // TODO might be able to ask which permissions it has and build an int
    // and String from there
    // clientListEntry.setPermissions();
    // clientListEntry.setPermissionsString();
    // No extended information
    clientListEntry.setExtended(null);
    return clientListEntry;
}

From source file:org.openspice.vfs.ftp.FtpVFolder.java

private List list(final boolean want_folders, final boolean want_files) {
    //      System.err.println( "folders = " + want_folders );
    //      System.err.println( "files = " + want_files );
    try {//from w  w  w.ja va 2 s.c o  m
        final FTPClient ftpc = this.fvol.getConnectedFTPClient();
        final FTPFile[] files = ftpc.listFiles(this.path);
        //         {
        //            System.err.println( "List of files is " + files.length + " long" );
        //            for ( int n = 0; n < files.length; n++ ) {
        //               System.err.println( "["+n+"]. " + files[n] + " " + ( files[n].isDirectory() ? "d" : "-" ) + ( files[n].isFile() ? "f" : "-" ) );
        //            }
        //         }
        final List answer = new ArrayList();
        for (int i = 0; i < files.length; i++) {
            final FTPFile file = files[i];
            if (want_folders && file.isDirectory()) {
                //               System.err.println( "adding FOLDER " + file );
                answer.add(new FtpVFolder(this.fvol, FtpTools.folderName(this.path, file.getName())));
            } else if (want_files && (file.isFile() || file.isSymbolicLink())) {
                //               System.err.println( "adding FILE " + file );
                answer.add(FtpVFile.uncheckedMake(this.fvol, FtpTools.fileName(this.path, file.getName())));
            }
        }
        return answer;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}