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

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

Introduction

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

Prototype

public boolean isDirectory() 

Source Link

Document

Determine if the file is a directory.

Usage

From source file:com.dp2345.plugin.ftp.FtpPlugin.java

@Override
public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
        String host = pluginConfig.getAttribute("host");
        Integer port = Integer.valueOf(pluginConfig.getAttribute("port"));
        String username = pluginConfig.getAttribute("username");
        String password = pluginConfig.getAttribute("password");
        String urlPrefix = pluginConfig.getAttribute("urlPrefix");
        FTPClient ftpClient = new FTPClient();
        try {/*ww w. j a va 2  s .c  o  m*/
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())
                    && ftpClient.changeWorkingDirectory(path)) {
                for (FTPFile ftpFile : ftpClient.listFiles()) {
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setName(ftpFile.getName());
                    fileInfo.setUrl(urlPrefix + path + ftpFile.getName());
                    fileInfo.setIsDirectory(ftpFile.isDirectory());
                    fileInfo.setSize(ftpFile.getSize());
                    fileInfo.setLastModified(ftpFile.getTimestamp().getTime());
                    fileInfos.add(fileInfo);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
    return fileInfos;
}

From source file:com.bdaum.zoom.ui.internal.wizards.FtpDirPage.java

private ContainerCheckedTreeViewer createViewerGroup(Composite comp) {
    urlLabel = new Label(comp, SWT.NONE);
    urlLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    ExpandCollapseGroup expandCollapseGroup = new ExpandCollapseGroup(comp, SWT.NONE);
    final ContainerCheckedTreeViewer cbViewer = new ContainerCheckedTreeViewer(comp,
            SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
    expandCollapseGroup.setViewer(cbViewer);
    final Tree tree = cbViewer.getTree();
    tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    cbViewer.setLabelProvider(new ZColumnLabelProvider() {
        @Override//from ww w.  jav  a 2s. c  o  m
        public String getText(Object element) {
            if (element instanceof FTPFile)
                return ((FTPFile) element).getName();
            return element.toString();
        }
    });
    cbViewer.setContentProvider(new ITreeContentProvider() {
        public void inputChanged(Viewer v, Object oldInput, Object newInput) {
            fileParents.clear();
            dirPaths.clear();
        }

        public void dispose() {
            fileParents.clear();
            dirPaths.clear();
        }

        public Object[] getElements(Object inputElement) {
            if (inputElement instanceof FTPClient) {
                FTPClient ftpClient = (FTPClient) inputElement;
                List<FTPFile> files = new ArrayList<FTPFile>();
                try {
                    FTPFile[] listFiles = ftpClient.listFiles();
                    for (FTPFile ftpFile : listFiles) {
                        if (ftpFile.isDirectory()) {
                            if (!ftpFile.getName().endsWith(".")) { //$NON-NLS-1$
                                files.add(ftpFile);
                                dirPaths.put(ftpFile, dir + '/' + ftpFile.getName());
                            }
                        } else if (filter.accept(ftpFile.getName()))
                            files.add(ftpFile);
                    }
                } catch (IOException e) {
                    // ignore
                }
                return files.toArray();
            }
            return new Object[0];
        }

        public boolean hasChildren(Object element) {
            if (element instanceof FTPFile)
                return ((FTPFile) element).isDirectory();
            return false;
        }

        public Object getParent(Object element) {
            return fileParents.get(element);
        }

        public Object[] getChildren(Object parentElement) {
            if (parentElement instanceof FTPFile) {
                FTPFile parent = (FTPFile) parentElement;
                if (parent.isDirectory()) {
                    String path = dirPaths.get(parent);
                    if (path != null)
                        try {
                            if (ftp.changeWorkingDirectory(path)) {
                                List<FTPFile> files = new ArrayList<FTPFile>();
                                for (FTPFile ftpFile : ftp.listFiles()) {
                                    if (ftpFile.isDirectory()) {
                                        if (!ftpFile.getName().endsWith(".")) { //$NON-NLS-1$
                                            files.add(ftpFile);
                                            dirPaths.put(ftpFile, path + '/' + ftpFile.getName());
                                        }
                                    } else if (filter.accept(ftpFile.getName()))
                                        files.add(ftpFile);
                                    fileParents.put(ftpFile, parent);
                                }
                                return files.toArray();
                            }
                        } catch (IOException e) {
                            // ignore
                        }
                }
            }
            return new Object[0];
        }
    });
    cbViewer.setComparator(new ViewerComparator() {
        @Override
        public int compare(Viewer v, Object e1, Object e2) {
            if (e1 instanceof FTPFile && e2 instanceof FTPFile) {
                int i1 = ((FTPFile) e1).isDirectory() ? 1 : 2;
                int i2 = ((FTPFile) e2).isDirectory() ? 1 : 2;
                if (i1 != i2)
                    return i1 - i2;
                return ((FTPFile) e1).getName().compareToIgnoreCase(((FTPFile) e2).getName());
            }
            return super.compare(v, e1, e2);
        }
    });
    cbViewer.addCheckStateListener(new ICheckStateListener() {
        public void checkStateChanged(CheckStateChangedEvent event) {
            validatePage();
        }
    });
    UiUtilities.installDoubleClickExpansion(cbViewer);
    return cbViewer;
}

From source file:com.feilong.tools.net.filetransfer.FTPUtil.java

/**
 * Log ftp file./*  w  ww  . j  a  v  a2s.com*/
 * 
 * @param ftpFile
 *            the ftp file
 */
private void logFTPFile(FTPFile ftpFile) {
    String ftpFileName = ftpFile.getName();
    Object[] params = { ftpFileName, ftpFile.isDirectory(), ftpFile.getType() };
    log.info("ftpFile Name:[{}] ,isDirectory:[{}],ftpFile type:[{}]", params);
}

From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java

@Override
public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    // PluginConfig pluginConfig = getPluginConfig();
    // if (pluginConfig != null) {
    Map<String, String> ftpInfo = getFtpInfo("all");
    String urlPrefix = DataConfig.getConfig("IMGFTPROOT");
    FTPClient ftpClient = new FTPClient();
    try {//from  w  w w . ja va  2  s.  c  o m
        ftpClient.connect(ftpInfo.get("host"), 21);
        ftpClient.login(ftpInfo.get("username"), ftpInfo.get("password"));
        ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()) && ftpClient.changeWorkingDirectory(path)) {
            for (FTPFile ftpFile : ftpClient.listFiles()) {
                FileInfo fileInfo = new FileInfo();
                fileInfo.setName(ftpFile.getName());
                fileInfo.setUrl(urlPrefix + path + ftpFile.getName());
                fileInfo.setIsDirectory(ftpFile.isDirectory());
                fileInfo.setSize(ftpFile.getSize());
                fileInfo.setLastModified(ftpFile.getTimestamp().getTime());
                fileInfos.add(fileInfo);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
            }
        }
    }
    // }
    return fileInfos;
}

From source file:com.feilong.tools.net.filetransfer.FTPUtil.java

@Override
protected Map<String, FileInfoEntity> getLsFileMap(String remotePath) throws Exception {
    Map<String, FileInfoEntity> map = new HashMap<String, FileInfoEntity>();
    FTPFile[] ftpFiles = ftpClient.listFiles(remotePath);
    for (FTPFile ftpFile : ftpFiles) {

        String filename = ftpFile.getName();

        boolean isDirectory = ftpFile.isDirectory();

        FileInfoEntity fileEntity = new FileInfoEntity();
        fileEntity.setFileType(isDirectory ? FileType.DIRECTORY : FileType.FILE);
        fileEntity.setName(filename);/*www  .ja v  a  2 s  . c o m*/
        fileEntity.setSize(ftpFile.getSize());
        fileEntity.setLastModified(ftpFile.getTimestamp().getTimeInMillis());

        map.put(filename, fileEntity);
    }
    return map;
}

From source file:ilarkesto.integration.ftp.FtpClient.java

public void deleteFile(String path) {
    FTPFile file = getFile(path);
    if (file == null)
        return;/*from  ww  w . j a  v  a 2 s . c  o  m*/

    log.info("Delete:", path);
    boolean deleted;
    try {
        deleted = file.isDirectory() ? client.removeDirectory(path) : client.deleteFile(path);
    } catch (IOException ex) {
        throw new RuntimeException("Deleting remote file failed: " + path, ex);
    }

    if (!deleted)
        throw new RuntimeException("Deleting remote file failed: " + path + " | " + client.getReplyString());
}

From source file:jenkins.plugins.publish_over_ftp.BapFtpClientTest.java

private FTPFile expectDirectory(final FTPListParseEngine mockListEngine, final String dirname) {
    final FTPFile dir = expectFtpFile(mockListEngine, dirname);
    expect(dir.isDirectory()).andReturn(true);
    return dir;/*from   ww  w.  j a  va  2s . co m*/
}

From source file:jenkins.plugins.publish_over_ftp.BapFtpClientTest.java

private FTPFile expectFile(final FTPListParseEngine mockListEngine, final String filename) {
    final FTPFile file = expectFtpFile(mockListEngine, filename);
    expect(file.isDirectory()).andReturn(false);
    return file;//from w w  w  . j a v a 2s. com
}

From source file:com.naryx.tagfusion.cfm.tag.net.ftp.FtpList.java

public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    cfFTPData ftpdata = getFTPData(_session, argStruct);

    boolean soe = getNamedBooleanParam(argStruct, "stoponerror", true);
    boolean passive = getNamedBooleanParam(argStruct, "passive", false);
    String directory = getNamedStringParam(argStruct, "directory", "/");
    if (!directory.endsWith("/"))
        directory += "/";

    // Perform the directory listing
    FTPFile[] files;/*  w  ww .  j  a va 2  s  .  c om*/
    try {
        ftpdata.lock();
        ftpdata.setPassive(passive);
        files = ftpdata.listFiles(directory);
        if (soe && !ftpdata.isSucceeded())
            throwException(_session, ftpdata.getErrorText());

    } finally {
        ftpdata.unlock();
    }

    // Returning a query
    cfQueryResultData queryFile = new cfQueryResultData(new String[] { "name", "path", "url", "length",
            "lastmodified", "attributes", "isdirectory", "mode" }, "CFFTP");

    if (!ftpdata.isSucceeded() || files.length == 0)
        return queryFile;

    // Fill out the query
    if (!directory.startsWith("/"))
        directory = "/" + directory;

    List<Map<String, cfData>> resultQuery = new ArrayList<Map<String, cfData>>(files.length);
    for (FTPFile ftpfile : files) {

        Map<String, cfData> HM = new FastMap<String, cfData>();

        HM.put("name", new cfStringData(ftpfile.getName()));
        HM.put("length", new cfNumberData(ftpfile.getSize()));
        HM.put("lastmodified", new cfDateData(ftpfile.getTimestamp().getTime().getTime()));
        HM.put("isdirectory", cfBooleanData.getcfBooleanData(ftpfile.isDirectory()));

        HM.put("path", new cfStringData(directory + ftpfile.getName()));
        HM.put("url", new cfStringData("ftp://" + ftpdata.getServer() + directory + ftpfile.getName()));
        HM.put("attributes", new cfStringData(ftpfile.isDirectory() ? "Directory" : "Normal"));

        String mode = getMode(ftpfile, FTPFile.USER_ACCESS);
        mode += getMode(ftpfile, FTPFile.GROUP_ACCESS);
        mode += getMode(ftpfile, FTPFile.WORLD_ACCESS);
        HM.put("mode", new cfStringData(mode));

        resultQuery.add(HM);
    }

    queryFile.populateQuery(resultQuery);
    return queryFile;
}

From source file:com.nononsenseapps.filepicker.sample.ftp.FtpPickerFragment.java

/**
 * Get a loader that lists the files in the current path,
 * and monitors changes.//  www.jav a2  s .co m
 */
@NonNull
@Override
public Loader<SortedList<FtpFile>> getLoader() {
    return new AsyncTaskLoader<SortedList<FtpFile>>(getContext()) {
        @Override
        public SortedList<FtpFile> loadInBackground() {
            SortedList<FtpFile> sortedList = new SortedList<>(FtpFile.class,
                    new SortedListAdapterCallback<FtpFile>(getDummyAdapter()) {
                        @Override
                        public int compare(FtpFile lhs, FtpFile rhs) {
                            if (lhs.isDirectory() && !rhs.isDirectory()) {
                                return -1;
                            } else if (rhs.isDirectory() && !lhs.isDirectory()) {
                                return 1;
                            } else {
                                return lhs.getName().compareToIgnoreCase(rhs.getName());
                            }
                        }

                        @Override
                        public boolean areContentsTheSame(FtpFile oldItem, FtpFile newItem) {
                            return oldItem.getName().equals(newItem.getName());
                        }

                        @Override
                        public boolean areItemsTheSame(FtpFile item1, FtpFile item2) {
                            return item1.getName().equals(item2.getName());
                        }
                    });

            if (!ftp.isConnected()) {
                // Connect
                try {
                    ftp.connect(server, port);

                    ftp.setFileType(FTP.ASCII_FILE_TYPE);
                    ftp.enterLocalPassiveMode();
                    ftp.setUseEPSVwithIPv4(false);

                    if (!(loggedIn = ftp.login(username, password))) {
                        ftp.logout();
                        Log.e(TAG, "Login failed");
                    }
                } catch (IOException e) {
                    if (ftp.isConnected()) {
                        try {
                            ftp.disconnect();
                        } catch (IOException ignored) {
                        }
                    }
                    Log.e(TAG, "Could not connect to server.");
                }
            }

            if (loggedIn) {
                try {
                    // handle if directory does not exist. Fall back to root.
                    if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
                        mCurrentPath = getRoot();
                    }

                    sortedList.beginBatchedUpdates();
                    for (FTPFile f : ftp.listFiles(mCurrentPath.getPath())) {
                        FtpFile file;
                        if (f.isDirectory()) {
                            file = new FtpDir(mCurrentPath, f.getName());
                        } else {
                            file = new FtpFile(mCurrentPath, f.getName());
                        }
                        if (isItemVisible(file)) {
                            sortedList.add(file);
                        }
                    }
                    sortedList.endBatchedUpdates();
                } catch (IOException e) {
                    Log.e(TAG, "IOException: " + e.getMessage());
                }
            }

            return sortedList;
        }

        /**
         * Handles a request to start the Loader.
         */
        @Override
        protected void onStartLoading() {
            super.onStartLoading();

            // handle if directory does not exist. Fall back to root.
            if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
                mCurrentPath = getRoot();
            }

            forceLoad();
        }
    };
}