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

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

Introduction

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

Prototype

public String getLink() 

Source Link

Document

If the FTPFile is a symbolic link, this method returns the name of the file being pointed to by the 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  .j  a v a 2s .  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  w ww  .ja  v a2 s .c o  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:ch.cyberduck.core.ftp.FTPListResponseReader.java

@Override
public AttributedList<Path> read(final Path directory, final List<String> replies,
        final ListProgressListener listener)
        throws IOException, FTPInvalidListException, ConnectionCanceledException {
    final AttributedList<Path> children = new AttributedList<Path>();
    // At least one entry successfully parsed
    boolean success = false;
    // Call hook for those implementors which need to perform some action upon the list after it has been created
    // from the server stream, but before any clients see the list
    parser.preParse(replies);/* w  w  w .j av  a 2s .c o m*/
    for (String line : replies) {
        final FTPFile f = parser.parseFTPEntry(line);
        if (null == f) {
            continue;
        }
        final String name = f.getName();
        if (!success) {
            if (lenient) {
                // Workaround for #2410. STAT only returns ls of directory itself
                // Workaround for #2434. STAT of symbolic link directory only lists the directory itself.
                if (directory.getName().equals(name)) {
                    log.warn(String.format("Skip %s matching parent directory name", f.getName()));
                    continue;
                }
                if (name.contains(String.valueOf(Path.DELIMITER))) {
                    if (!name.startsWith(directory.getAbsolute() + Path.DELIMITER)) {
                        // Workaround for #2434.
                        log.warn(String.format("Skip %s with delimiter in name", name));
                        continue;
                    }
                }
            }
        }
        success = true;
        if (name.equals(".") || name.equals("..")) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Skip %s", f.getName()));
            }
            continue;
        }
        final Path parsed = new Path(directory, PathNormalizer.name(name),
                f.getType() == FTPFile.DIRECTORY_TYPE ? EnumSet.of(Path.Type.directory)
                        : EnumSet.of(Path.Type.file));
        switch (f.getType()) {
        case FTPFile.SYMBOLIC_LINK_TYPE:
            parsed.setType(EnumSet.of(Path.Type.file, Path.Type.symboliclink));
            // Symbolic link target may be an absolute or relative path
            final String target = f.getLink();
            if (StringUtils.isBlank(target)) {
                log.warn(String.format("Missing symbolic link target for %s", parsed));
                final EnumSet<AbstractPath.Type> type = parsed.getType();
                type.remove(AbstractPath.Type.symboliclink);
            } else if (StringUtils.startsWith(target, String.valueOf(Path.DELIMITER))) {
                parsed.setSymlinkTarget(new Path(target, EnumSet.of(Path.Type.file)));
            } else if (StringUtils.equals("..", target)) {
                parsed.setSymlinkTarget(directory);
            } else if (StringUtils.equals(".", target)) {
                parsed.setSymlinkTarget(parsed);
            } else {
                parsed.setSymlinkTarget(new Path(directory, target, EnumSet.of(Path.Type.file)));
            }
            break;
        }
        if (parsed.isFile()) {
            parsed.attributes().setSize(f.getSize());
        }
        parsed.attributes().setOwner(f.getUser());
        parsed.attributes().setGroup(f.getGroup());
        Permission.Action u = Permission.Action.none;
        if (f.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION)) {
            u = u.or(Permission.Action.read);
        }
        if (f.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION)) {
            u = u.or(Permission.Action.write);
        }
        if (f.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION)) {
            u = u.or(Permission.Action.execute);
        }
        Permission.Action g = Permission.Action.none;
        if (f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION)) {
            g = g.or(Permission.Action.read);
        }
        if (f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION)) {
            g = g.or(Permission.Action.write);
        }
        if (f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)) {
            g = g.or(Permission.Action.execute);
        }
        Permission.Action o = Permission.Action.none;
        if (f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION)) {
            o = o.or(Permission.Action.read);
        }
        if (f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION)) {
            o = o.or(Permission.Action.write);
        }
        if (f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)) {
            o = o.or(Permission.Action.execute);
        }
        final Permission permission = new Permission(u, g, o);
        if (f instanceof FTPExtendedFile) {
            permission.setSetuid(((FTPExtendedFile) f).isSetuid());
            permission.setSetgid(((FTPExtendedFile) f).isSetgid());
            permission.setSticky(((FTPExtendedFile) f).isSticky());
        }
        parsed.attributes().setPermission(permission);
        final Calendar timestamp = f.getTimestamp();
        if (timestamp != null) {
            parsed.attributes().setModificationDate(timestamp.getTimeInMillis());
        }
        children.add(parsed);
    }
    if (!success) {
        throw new FTPInvalidListException(children);
    }
    return children;
}

From source file:ch.cyberduck.core.ftp.FTPPath.java

protected boolean parseListResponse(final AttributedList<Path> children, final FTPFileEntryParser parser,
        final List<String> replies) {
    if (null == replies) {
        // This is an empty directory
        return false;
    }/* w ww .j  av a  2  s.c om*/
    boolean success = false;
    for (String line : replies) {
        final FTPFile f = parser.parseFTPEntry(line);
        if (null == f) {
            continue;
        }
        final String name = f.getName();
        if (!success) {
            // Workaround for #2410. STAT only returns ls of directory itself
            // Workaround for #2434. STAT of symbolic link directory only lists the directory itself.
            if (this.getAbsolute().equals(name)) {
                log.warn(String.format("Skip %s", f.getName()));
                continue;
            }
            if (name.contains(String.valueOf(DELIMITER))) {
                if (!name.startsWith(this.getAbsolute() + Path.DELIMITER)) {
                    // Workaround for #2434.
                    log.warn("Skip listing entry with delimiter:" + name);
                    continue;
                }
            }
        }
        success = true;
        if (name.equals(".") || name.equals("..")) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Skip %s", f.getName()));
            }
            continue;
        }
        final Path parsed = new FTPPath(this.getSession(), this.getAbsolute(),
                StringUtils.removeStart(name, this.getAbsolute() + Path.DELIMITER),
                f.getType() == FTPFile.DIRECTORY_TYPE ? DIRECTORY_TYPE : FILE_TYPE);
        parsed.setParent(this);
        switch (f.getType()) {
        case FTPFile.SYMBOLIC_LINK_TYPE:
            parsed.setSymlinkTarget(f.getLink());
            parsed.attributes().setType(SYMBOLIC_LINK_TYPE | FILE_TYPE);
            break;
        }
        if (parsed.attributes().isFile()) {
            parsed.attributes().setSize(f.getSize());
        }
        parsed.attributes().setOwner(f.getUser());
        parsed.attributes().setGroup(f.getGroup());
        if (this.getSession().isPermissionSupported(parser)) {
            parsed.attributes()
                    .setPermission(
                            new Permission(new boolean[][] {
                                    { f.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION),
                                            f.hasPermission(FTPFile.USER_ACCESS,
                                                    FTPFile.WRITE_PERMISSION),
                                            f.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION) },
                                    { f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION),
                                            f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION),
                                            f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION) },
                                    { f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION),
                                            f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION),
                                            f.hasPermission(FTPFile.WORLD_ACCESS,
                                                    FTPFile.EXECUTE_PERMISSION) } }));
        }
        final Calendar timestamp = f.getTimestamp();
        if (timestamp != null) {
            parsed.attributes().setModificationDate(timestamp.getTimeInMillis());
        }
        children.add(parsed);
    }
    return success;
}

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 2  s  . 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: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 a va 2s . co m*/

    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:nl.esciencecenter.xenon.adaptors.filesystems.ftp.FtpFileSystem.java

@Override
public Path readSymbolicLink(Path path) throws XenonException {

    Path absPath = toAbsolutePath(path);

    FTPFile file = getFTPFileInfo(absPath);

    if (file.getType() != FTPFile.SYMBOLIC_LINK_TYPE) {
        throw new InvalidPathException(ADAPTOR_NAME, "Path is not a symbolic link: " + absPath);
    }/*from www .  j  a  va 2 s  .c  o m*/

    return new Path(file.getLink());
}

From source file:nl.nn.adapterframework.filesystem.FtpFileSystem.java

@Override
public Map<String, Object> getAdditionalFileProperties(FTPFile f) {
    Map<String, Object> attributes = new HashMap<String, Object>();
    attributes.put("user", f.getUser());
    attributes.put("group", f.getGroup());
    attributes.put("type", f.getType());
    attributes.put("rawListing", f.getRawListing());
    attributes.put("link", f.getLink());
    attributes.put("hardLinkCount", f.getHardLinkCount());
    return attributes;
}

From source file:org.amanzi.neo.geoptima.loader.core.parser.impl.FtpDataParser.java

/**
 * @param ftpClient/* w  w w .  j  av a 2  s.  c o  m*/
 * @param files
 * @param folder
 * @throws IOException
 */
private void uploadData(final FTPClient ftpClient, final FTPFile[] files, final File folder,
        final FTPFile source) throws IOException {
    try {
        for (FTPFile file : files) {
            if (file.isDirectory()) {
                File newFolder = createFolder(folder.getAbsolutePath() + File.separator + file.getName());
                uploadData(ftpClient, getFiles(ftpClient, file), newFolder, file);
            } else {
                FileOutputStream fos = new FileOutputStream(
                        folder.getAbsolutePath() + File.separator + file.getName());
                LOGGER.info("<Downloading file " + file.getName() + " to directory " + folder.getAbsolutePath()
                        + ">");
                ftpClient.retrieveFile(file.getLink(), fos);
                fos.close();
            }
        }
    } catch (IOException e) {
        LOGGER.error("can't upload file ", e);
        throw e;
    }
}

From source file:org.amanzi.neo.geoptima.loader.core.parser.impl.FtpDataParser.java

/**
 * @param ftpClient/*from w ww .  ja v a 2  s. c  o m*/
 * @param file
 * @return
 * @throws IOException
 */
private FTPFile[] getFiles(final FTPClient ftpClient, final FTPFile file) throws IOException {
    FTPFile[] files = ftpClient.listFiles(file.getLink(), FTP_FILE_FILTER);
    for (FTPFile innerFile : files) {
        innerFile.setLink(file.getLink() + "/" + innerFile.getName());
    }
    return files;
}