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

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Return the name of the file.

Usage

From source file:lucee.runtime.tag.Ftp.java

/**
 * List data of a ftp connection//from   w w w .j  ava  2  s  . com
 * @return FTPCLient
 * @throws PageException
 * @throws IOException
 */
private FTPClient actionListDir() throws PageException, IOException {
    required("name", name);
    required("directory", directory);

    FTPClient client = getClient();
    FTPFile[] files = client.listFiles(directory);
    if (files == null)
        files = new FTPFile[0];

    String[] cols = new String[] { "attributes", "isdirectory", "lastmodified", "length", "mode", "name",
            "path", "url", "type", "raw" };
    String[] types = new String[] { "VARCHAR", "BOOLEAN", "DATE", "DOUBLE", "VARCHAR", "VARCHAR", "VARCHAR",
            "VARCHAR", "VARCHAR", "VARCHAR" };

    lucee.runtime.type.Query query = new QueryImpl(cols, types, 0, "query");

    // translate directory path for display
    if (directory.length() == 0)
        directory = "/";
    else if (directory.startsWith("./"))
        directory = directory.substring(1);
    else if (directory.charAt(0) != '/')
        directory = '/' + directory;
    if (directory.charAt(directory.length() - 1) != '/')
        directory = directory + '/';

    pageContext.setVariable(name, query);
    int row = 0;
    for (int i = 0; i < files.length; i++) {
        FTPFile file = files[i];
        if (file.getName().equals(".") || file.getName().equals(".."))
            continue;
        query.addRow();
        row++;
        query.setAt("attributes", row, "");
        query.setAt("isdirectory", row, Caster.toBoolean(file.isDirectory()));
        query.setAt("lastmodified", row, new DateTimeImpl(file.getTimestamp()));
        query.setAt("length", row, Caster.toDouble(file.getSize()));
        query.setAt("mode", row, FTPConstant.getPermissionASInteger(file));
        query.setAt("type", row, FTPConstant.getTypeAsString(file.getType()));
        //query.setAt("permission",row,FTPConstant.getPermissionASInteger(file));
        query.setAt("raw", row, file.getRawListing());
        query.setAt("name", row, file.getName());
        query.setAt("path", row, directory + file.getName());
        query.setAt("url", row,
                "ftp://" + client.getRemoteAddress().getHostName() + "" + directory + file.getName());
    }
    writeCfftp(client);
    return client;
}

From source file:de.aw.awlib.fragments.AWRemoteFileChooser.java

@Override
public void onBindViewHolder(AWLibViewHolder holder, FTPFile file, int position) {
    TextView tv;//w w w  .  ja v a 2 s. c  om
    switch (holder.getItemViewType()) {
    case BACKTOPARENT:
        for (int resID : viewResIDs) {
            View view = holder.itemView.findViewById(resID);
            if (resID == R.id.folderImage) {
                ImageView img = (ImageView) view;
                img.setImageResource(R.drawable.ic_open_folder);
            } else if (resID == R.id.awlib_fileName) {
                tv = (TextView) view;
                if (mDirectoyList.size() == 0) {
                    tv.setText(".");
                } else {
                    tv.setText(file.getName());
                }
            } else if (resID == R.id.awlib_fileData) {
                view.setVisibility(View.GONE);
            }
        }
        break;
    default:
        for (int resID : viewResIDs) {
            View view = holder.itemView.findViewById(resID);
            if (resID == R.id.folderImage) {
                ImageView img = (ImageView) view;
                if (file.isDirectory()) {
                    img.setImageResource(R.drawable.ic_closed_folder);
                } else {
                    img.setImageResource(R.drawable.ic_file_generic);
                }
            } else if (resID == R.id.awlib_fileName) {
                tv = (TextView) view;
                tv.setText(file.getName());
            } else if (resID == R.id.awlib_fileData) {
                view.setVisibility(View.VISIBLE);
                tv = (TextView) view;
                tv.setText(Formatter.formatFileSize(getContext(), file.getSize()));
            }
        }
    }
}

From source file:com.datos.vfs.provider.ftp.FtpFileObject.java

/**
 * Fetches the children of this file, if not already cached.
 *//*from ww w. ja v a 2s .  c om*/
private void doGetChildren() throws IOException {
    if (children != null) {
        return;
    }

    final FtpClient client = getAbstractFileSystem().getClient();
    try {
        final String path = fileInfo != null && fileInfo.isSymbolicLink()
                ? getFileSystem().getFileSystemManager().resolveName(getParent().getName(), fileInfo.getLink())
                        .getPath()
                : relPath;
        final FTPFile[] tmpChildren = client.listFiles(path);
        if (tmpChildren == null || tmpChildren.length == 0) {
            children = EMPTY_FTP_FILE_MAP;
        } else {
            children = new TreeMap<>();

            // Remove '.' and '..' elements
            for (int i = 0; i < tmpChildren.length; i++) {
                final FTPFile child = tmpChildren[i];
                if (child == null) {
                    if (log.isDebugEnabled()) {
                        log.debug(Messages.getString("vfs.provider.ftp/invalid-directory-entry.debug",
                                Integer.valueOf(i), relPath));
                    }
                    continue;
                }
                if (!".".equals(child.getName()) && !"..".equals(child.getName())) {
                    children.put(child.getName(), child);
                }
            }
        }
    } finally {
        getAbstractFileSystem().putClient(client);
    }
}

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;
    }//from w w  w  .j a v a2 s  . co  m
    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.maxl.java.aips2sqlite.AllDown.java

public void downDesitin() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {/*from  w w w  .j a va 2  s  . c o  m*/
        FileInputStream access = new FileInputStream(Constants.DIR_DESITIN + "/access.ami.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(access, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            // Semicolon is used as a separator
            String[] gln = line.split(";");
            if (gln.length > 2) {
                if (gln[0].equals("ftp_amiko")) {
                    fl = gln[0];
                    fp = gln[1];
                    fs = gln[2];
                }
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FTPClient ftp_client = new FTPClient();
    try {
        ftp_client.connect(fs, 21);
        ftp_client.login(fl, fp);
        ftp_client.enterLocalPassiveMode();
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        System.out.println("- Connected to server " + fs + "...");

        // Set working directory
        String working_dir = "ywesee_in";
        ftp_client.changeWorkingDirectory(working_dir);
        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }
        // Get list of filenames
        FTPFile[] ftpFiles = ftp_client.listFiles();
        if (ftpFiles != null && ftpFiles.length > 0) {
            // ... then download all csv files
            for (FTPFile f : ftpFiles) {
                String remote_file = f.getName();
                if (remote_file.endsWith("csv")) {
                    String local_file = remote_file;
                    if (remote_file.startsWith("Kunden"))
                        local_file = Constants.FILE_CUST_DESITIN;
                    if (remote_file.startsWith("Artikel"))
                        local_file = Constants.FILE_ARTICLES_DESITIN;
                    OutputStream os = new FileOutputStream(Constants.DIR_DESITIN + "/" + local_file);
                    System.out.print("- Downloading " + remote_file + " from server " + fs + "... ");
                    boolean done = ftp_client.retrieveFile(remote_file, os);
                    if (done)
                        System.out.println("success.");
                    else
                        System.out.println("error.");
                    os.close();
                }
            }
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downZurRose() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {/*from   w  w  w.j  a  v  a  2  s  .  c  om*/
        FileInputStream access = new FileInputStream(Constants.DIR_ZURROSE + "/access.ami.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(access, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            // Semicolon is used as a separator
            String[] gln = line.split(";");
            if (gln.length > 2) {
                if (gln[0].equals("P_ywesee")) {
                    fl = gln[0];
                    fp = gln[1];
                    fs = gln[2];
                }
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FTPClient ftp_client = new FTPClient();
    try {
        ftp_client.connect(fs, 21);
        ftp_client.login(fl, fp);
        ftp_client.enterLocalPassiveMode();
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        System.out.println("- Connected to server " + fs + "...");

        String[] working_dir = { "ywesee out", "../ywesee in" };

        for (int i = 0; i < working_dir.length; ++i) {
            // Set working directory
            ftp_client.changeWorkingDirectory(working_dir[i]);
            int reply = ftp_client.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp_client.disconnect();
                System.err.println("FTP server refused connection.");
                return;
            }
            // Get list of filenames
            FTPFile[] ftpFiles = ftp_client.listFiles();
            if (ftpFiles != null && ftpFiles.length > 0) {
                // ... then download all csv files
                for (FTPFile f : ftpFiles) {
                    String remote_file = f.getName();
                    if (remote_file.endsWith("csv")) {
                        String local_file = remote_file;
                        if (remote_file.startsWith("Artikelstamm"))
                            local_file = Constants.CSV_FILE_DISPO_ZR;
                        OutputStream os = new FileOutputStream(Constants.DIR_ZURROSE + "/" + local_file);
                        System.out.print("- Downloading " + remote_file + " from server " + fs + "... ");
                        boolean done = ftp_client.retrieveFile(remote_file, os);
                        if (done)
                            System.out.println("success.");
                        else
                            System.out.println("error.");
                        os.close();
                    }
                }
            }
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

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

/**
 * return the size of remote-file on the remote machine on success, otherwise -1
 * @param remoteFile the file on remote machine
 * @return the size of remote-file on remote machine
 *///from w  w  w.  ja v a 2s . c  o  m
@Override
public long size(final String remoteFile) throws Exception {

    //      Client().sendCommand("NOOP");
    //      LogReply();
    //      LogReply();
    //      LogReply();

    if (listFiles != null && 1 == 0) {
        for (FTPFile objFile : listFiles) {
            if (objFile.getName().equalsIgnoreCase(remoteFile)) {
                return objFile.getSize();
            }
        }
        return -1L;
    } else {
        Client().sendCommand("SIZE " + remoteFile);
        LogReply();
        if (Client().getReplyCode() == FTPReply.CODE_213)
            return Long.parseLong(trimResponseCode(this.getReplyString()));
        else
            return -1L; // file not found or size not available
    }
}

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

/**
 * return a listing of the contents of a directory in short format on
 * the remote machine (without subdirectory)
 *
 * @param pathname on remote machine/*w w  w. ja v  a 2s.  co m*/
 * @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 conMethodName = "getFilenames";
    String strCurrentDirectory = null;
    // TODO vecDirectoryListing = null; prfen, ob notwendig
    Vector<String> 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;
        }

        //         if (1 == 1) {
        //            try {
        //               fileList = listNames(lstrPathName);
        //            }
        //            catch (IOException e) {
        //               e.printStackTrace(System.err);
        //            }
        //         }

        try {
            listFiles = Client().listFiles(lstrPathName);
        } catch (IOException e) {
            RaiseException(e, HostID(SOSVfs_E_0105.params(conMethodName)));
        }

        if (listFiles == null || listFiles.length <= 0) {
            return vecDirectoryListing;
        }

        for (FTPFile listFile : listFiles) {
            String strCurrentFile = listFile.getName();
            if (isNotHiddenFile(strCurrentFile) && strCurrentFile.trim().length() > 0) {
                //               DoCD(strCurrentFile); // is this file-entry a subfolder?
                //               boolean flgIsDirectory = isNegativeCommandCompletion() == false;
                boolean flgIsDirectory = listFile.isDirectory();
                if (flgIsDirectory == false) {
                    if (lstrPathName.startsWith("/") == false) { // JIRA SOSFTP-124
                        if (strCurrentFile.startsWith(strCurrentDirectory) == false) {
                            strCurrentFile = addFileSeparator(strCurrentDirectory) + strCurrentFile;
                        }
                    }
                    vecDirectoryListing.add(strCurrentFile);
                } else {
                    if (flgIsDirectory && flgRecurseSubFolders == true) {
                        DoCD(strCurrentDirectory);
                        if (flgRecurseSubFolders) {
                            logger.debug(String.format(""));
                            Vector<String> vecNames = getFilenames(strCurrentFile, flgRecurseSubFolders);
                            if (vecNames != null) {
                                vecDirectoryListing.addAll(vecNames);
                            }
                        }
                    }
                }
            }
        }
    }
    logger.debug("strCurrentDirectory = " + strCurrentDirectory);
    if (strCurrentDirectory != null) {
        DoCD(strCurrentDirectory);
        DoPWD();
    }
    return vecDirectoryListing;
}

From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java

/**
 * @see it.greenvulcano.util.remotefs.RemoteManager#ls(String, String, date,
 *      int, java.util.Map)//  w w w  .j  a  va  2  s .c  om
 */
@Override
public Set<FileProperties> ls(String remoteDirectory, String filenamePattern, Date modifiedSince,
        int fileTypeFilter, Map<String, String> optProperties) throws RemoteManagerException {
    checkConnected();

    Set<FileProperties> resultsSet = new HashSet<FileProperties>();
    try {
        changeWorkingDirectory(remoteDirectory);

        FTPFile[] results = ftpClient.listFiles();
        int detectedFiles = (results != null ? results.length : 0);
        logger.debug(detectedFiles + " file entries DETECTED into current remote working directory");

        if (results != null) {
            RegExFileFilter fileFilter = new RegExFileFilter(filenamePattern, fileTypeFilter,
                    (modifiedSince != null) ? modifiedSince.getTime() : -1);
            for (FTPFile currFTPFile : results) {
                if (currFTPFile != null) {
                    if (fileFilter.accept(currFTPFile)) {
                        FileProperties currFile = new FileProperties(currFTPFile.getName(),
                                currFTPFile.getTimestamp().getTimeInMillis(), currFTPFile.getSize(),
                                currFTPFile.isDirectory(),
                                currFTPFile.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION),
                                currFTPFile.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION),
                                currFTPFile.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION));
                        resultsSet.add(currFile);
                    }
                } else {
                    logger.debug("Remote file entry NULL");
                }
            }
        }
        return resultsSet;
    } catch (Exception exc) {
        throw new RemoteManagerException("FTP directory scan error", exc);
    } finally {
        if (isAutoconnect()) {
            disconnect();
        }
    }
}

From source file:adams.core.io.lister.FtpDirectoryLister.java

/**
 * Performs the recursive search. Search goes deeper if != 0 (use -1 to
 * start with for infinite search).//from   w w  w.j  a v  a2s  .  co m
 *
 * @param client   the client to use
 * @param current   the current directory
 * @param files   the files collected so far
 * @param depth   the depth indicator (searched no deeper, if 0)
 * @throws Exception   if listing fails
 */
protected void search(FTPClient client, String current, List<SortContainer> files, int depth) throws Exception {
    List<FTPFile> currFiles;
    int i;
    FTPFile entry;
    SortContainer cont;

    if (depth == 0)
        return;

    if (getDebug())
        getLogger().info("search: current=" + current + ", depth=" + depth);

    client.changeWorkingDirectory(current);
    currFiles = new ArrayList<>();
    currFiles.addAll(Arrays.asList(client.listFiles()));
    if (currFiles.size() == 0) {
        if (getDebug())
            getLogger().info("No files listed!");
        return;
    }

    for (i = 0; i < currFiles.size(); i++) {
        // do we have to stop?
        if (m_Stopped)
            break;

        entry = currFiles.get(i);

        // directory?
        if (entry.isDirectory()) {
            // ignore "." and ".."
            if (entry.getName().equals(".") || entry.getName().equals(".."))
                continue;

            // search recursively?
            if (m_Recursive)
                search(client, current + "/" + entry.getName(), files, depth - 1);

            if (m_ListDirs) {
                // does name match?
                if (!m_RegExp.isEmpty() && !m_RegExp.isMatch(entry.getName()))
                    continue;

                files.add(new SortContainer(new FtpFileObject(current, entry, m_Client), m_Sorting));
            }
        } else {
            if (m_ListFiles) {
                // does name match?
                if (!m_RegExp.isEmpty() && !m_RegExp.isMatch(entry.getName()))
                    continue;

                files.add(new SortContainer(new FtpFileObject(current, entry, m_Client), m_Sorting));
            }
        }
    }
}