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:org.wso2.carbon.esb.scenario.test.common.ftp.FTPClientWrapper.java

/**
 * Function to list files of a directory on an FTP server.
 *
 * @param filePath file path to list files
 * @return list of files//  www  .  j  a va 2s.  c o m
 * @throws IOException if listing set of files fails
 */
public List<FTPFile> listFiles(String filePath) throws IOException {
    List<FTPFile> files = new ArrayList<>();
    try {
        FTPFile[] filesAndDirectories = ftpClient.listFiles(filePath);

        for (FTPFile file : filesAndDirectories) {
            if (!file.isDirectory()) {
                files.add(file);
            }
        }
    } catch (IOException ex) {
        throw new IOException("Error occurred while listing files", ex);
    }
    return files;
}

From source file:proyectoftp.controlador.Controlador.java

private void descargarFichero() {

    int pos, correcto;
    boolean descargar;
    String fichero;/*from w w  w.  j  av a2s .  c  o m*/
    FTPFile fFTP;

    JFileChooser exploradorArchivos = new JFileChooser();
    pos = vistaPrincipal.devolverPulsadoLista();

    if (pos <= -1) {
        JOptionPane.showMessageDialog(vistaPrincipal, "Debes de pulsar un archivo para poder descargarlo.",
                "Error", JOptionPane.ERROR_MESSAGE);
    } else {
        fichero = vistaPrincipal.devolverObjeto(pos);
        fFTP = new FTPFile();
        fFTP.setName(fichero);
        if (fFTP.isDirectory()) {
            JOptionPane.showMessageDialog(vistaPrincipal, "Debes seleccionar un fichero para descargar.",
                    "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            correcto = exploradorArchivos.showOpenDialog(vistaPrincipal);
            if (correcto == JFileChooser.APPROVE_OPTION) {
                File file = exploradorArchivos.getSelectedFile();

                try {

                    descargar = clienteFtp.descargarFichero(file.getCanonicalPath(), fFTP.getName());
                    comprobarDescargas(descargar);
                } catch (IOException ex) {
                    Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

        }

    }
}

From source file:pt.lsts.neptus.util.logdownload.LogsDownloaderWorkerActions.java

/**
 * Process the serversLogPresenceList and gets the actual log files/folder for each base log folder. This is done by
 * iterating the {@link LogsDownloaderWorker#getServersList()} depending on its presence.
 * /*  w ww.j a v  a2s.c  o m*/
 * @param serversLogPresenceList Map for each base log folder and servers presence as values (space separated list
 *            of servers keys)
 * @return
 */
private LinkedList<LogFolderInfo> getFromServersCompleteLogList(
        LinkedHashMap<String, String> serversLogPresenceList) {
    if (serversLogPresenceList.size() == 0)
        return new LinkedList<LogFolderInfo>();

    long timeF0 = System.currentTimeMillis();

    LinkedList<LogFolderInfo> tmpLogFolders = new LinkedList<LogFolderInfo>();

    try {
        ArrayList<String> servers = worker.getServersList();
        for (String serverKey : servers) { // Let's iterate by servers first
            if (stopLogListProcessing)
                break;

            if (!worker.isServerAvailable(serverKey))
                continue;

            FtpDownloader ftpServer = null;
            try {
                ftpServer = LogsDownloaderWorkerUtil.getOrRenewFtpDownloader(serverKey,
                        worker.getFtpDownloaders(), worker.getHostFor(serverKey), worker.getPortFor(serverKey));
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (ftpServer == null)
                continue;

            // String host = worker.getHostFor(serverKey); // To fill the log files host info
            String host = serverKey; // Using a key instead of host directly

            for (String logDir : serversLogPresenceList.keySet()) { // For the server go through the folders
                if (stopLogListProcessing)
                    break;

                if (!serversLogPresenceList.get(logDir).contains(serverKey))
                    continue;

                // This is needed to avoid problems with non English languages
                String isoStr = new String(logDir.getBytes(), "ISO-8859-1");

                LogFolderInfo lFolder = null;
                for (LogFolderInfo lfi : tmpLogFolders) {
                    if (lfi.getName().equals(logDir)) {
                        lFolder = lfi;
                        break;
                    }
                }
                if (lFolder == null)
                    lFolder = new LogFolderInfo(logDir);

                if (!ftpServer.isConnected())
                    ftpServer.renewClient();

                try {
                    FTPFile[] files = ftpServer.getClient().listFiles("/" + isoStr + "/");
                    for (FTPFile file : files) {
                        if (stopLogListProcessing)
                            break;

                        String name = logDir + "/" + file.getName();
                        String uriPartial = logDir + "/" + file.getName();
                        LogFileInfo logFileTmp = new LogFileInfo(name);
                        logFileTmp.setUriPartial(uriPartial);
                        logFileTmp.setSize(file.getSize());
                        logFileTmp.setFile(file);
                        logFileTmp.setHost(host);

                        // Let us see if its a directory
                        if (file.isDirectory()) {
                            logFileTmp.setSize(-1); // Set size to -1 if directory
                            long allSize = 0;

                            // Here there are no directories, considering only 2 folder layers only, e.g. "Photos/00000"
                            LinkedHashMap<String, FTPFile> dirListing = ftpServer
                                    .listDirectory(logFileTmp.getName());
                            ArrayList<LogFileInfo> directoryContents = new ArrayList<>();
                            for (String fName : dirListing.keySet()) {
                                if (stopLogListProcessing)
                                    break;

                                FTPFile fFile = dirListing.get(fName);
                                String fURIPartial = fName;
                                LogFileInfo fLogFileTmp = new LogFileInfo(fName);
                                fLogFileTmp.setUriPartial(fURIPartial);
                                fLogFileTmp.setSize(fFile.getSize());
                                fLogFileTmp.setFile(fFile);
                                fLogFileTmp.setHost(host);

                                allSize += fLogFileTmp.getSize();
                                directoryContents.add(fLogFileTmp);
                            }
                            logFileTmp.setDirectoryContents(directoryContents);
                            logFileTmp.setSize(allSize);
                        }
                        lFolder.addFile(logFileTmp);
                        tmpLogFolders.add(lFolder);
                    }
                } catch (Exception e) {
                    System.err.println(isoStr);
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    NeptusLog.pub().warn(".......Contacting remote systems for complete log file list "
            + (System.currentTimeMillis() - timeF0) + "ms");

    return tmpLogFolders;
}

From source file:restGateWay.HTMLGenerator.java

/**
 * This method return HTML source code than provide user to browse files, or retrive one
 *
 * @param file list of Files/* w w  w .j  av  a  2  s . c  o m*/
 * @return String containing HTML part containing href link 
 */
private String getLinkForFileName(String cwd, FTPFile file) {
    String tmp = "";
    if (file.isDirectory())
        tmp += "<img src=\"http://agingparentsauthority.com/wp-content/plugins/sem-theme-pro/icons/folder.png\" alt=\"[   ]\" />       <a href='"
                + path + "resources/file" + cwd + "/" + file.getName() + "'>" + file.getName() + "</a></br>\n";
    if (file.isFile()) {
        tmp += "<img src=\"http://www.appropedia.org/skins/vector/images/file-icon.png\" alt=\"[   ]\" /> "
                + "<a href=\"" + path + "/resources/file/" + cwd + "/delete/" + file.getName()
                + "\"><img src=\"http://www.domainedesnoms.com/themes/site/ddn.fr/images/picto/delete.png\" /></a> "
                + "<a href=\"" + path + "/resources/file/" + cwd + "/download/" + file.getName() + "\">"
                + file.getName() + "</a></br>";
    }
    return tmp;
}

From source file:savant.thousandgenomes.FTPBrowser.java

public FTPBrowser(URL rootURL) throws IOException {
    setRoot(rootURL);//from   w ww  .j  a va2 s .  c om

    setLayout(new BorderLayout());

    addressField = new JTextField();
    addressField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            try {
                setRoot(new URL(addressField.getText()));
                updateDirectory();
            } catch (Exception x) {
                DialogUtils.displayException("1000 Genomes Plugin", "Unable to change root directory", x);
            }
        }

    });
    add(addressField, BorderLayout.NORTH);

    table = new JTable();
    updateDirectory();

    table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent evt) {
            if (evt.getClickCount() == 2) {
                int row = table.rowAtPoint(evt.getPoint());
                try {
                    FTPFile f = ((FTPTableModel) table.getModel()).getEntry(row);
                    if (f == null) {
                        // Going up a directory.
                        curDir = curDir.getParentFile();
                        updateDirectory();
                    } else if (f.isDirectory()) {
                        curDir = new File(curDir, f.getName());
                        updateDirectory();
                    } else {
                        TrackUtils.createTrack(new URI(
                                "ftp://" + host + new File(curDir, f.getName()).getPath().replace("\\", "/")));
                    }
                } catch (Throwable x) {
                    DialogUtils.displayException("FTP Error", "Unable to process FTP request.", x);
                }
            }
        }
    });

    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.getViewport().setBackground(Color.WHITE);
    scrollPane.setPreferredSize(new Dimension(800, 500));
    add(scrollPane, BorderLayout.CENTER);

    this.setPreferredSize(new Dimension(800, 500));
}

From source file:savant.thousandgenomes.FTPBrowser.java

/**
 * Use the Swing FileSystemView to get a system icon corresponding to the given
 * file.//  w  ww  . j a v a2  s .  co m
 *
 * @param f the FTP entry whose icon we want to retrieve
 * @return a system icon representing f
 */
private static Icon getIcon(FTPFile f) {
    if (f == null || f.isDirectory()) {
        return FileSystemView.getFileSystemView().getSystemIcon(new File("."));
    } else {
        String name = f.getName();
        int ind = name.lastIndexOf(".");
        if (ind > 0) {
            String ext = name.substring(ind + 1);
            try {
                File tempFile = File.createTempFile("temp_icon.", "." + ext);
                Icon i = FileSystemView.getFileSystemView().getSystemIcon(tempFile);
                tempFile.delete();
                return i;
            } catch (IOException ex) {
            }
        }
    }
    return null;
}

From source file:sos.net.SOSFTP.java

/**
 * return a listing of a directory in long format on
 * the remote machine/*from  w w w  . j  ava  2 s .  c  om*/
 * @param pathname on remote machine
 * @return a listing of the contents of a directory on the remote machine
 * @exception Exception
 * @see #nList()
 * @see #nList( String )
 * @see #dir()
 * @deprecated
 */
@Deprecated
public Vector<String> dir(final String pathname, final int flag) throws Exception {

    Vector<String> fileList = new Vector<String>();
    FTPFile[] listFiles = listFiles(pathname);
    for (FTPFile listFile : listFiles) {
        if (flag > 0 && listFile.isDirectory()) {
            fileList.addAll(this.dir(pathname + "/" + listFile.toString(), flag >= 1024 ? flag : flag + 1024));
        } else {
            if (flag >= 1024) {
                fileList.add(pathname + "/" + listFile.toString());
            } else {
                fileList.add(listFile.toString());
            }
        }
    }
    return fileList;
}

From source file:tv.icntv.log.crawl.core.FtpImpl.java

@Override
public boolean downLoadDirectory(String localDirectoryPath, String remoteDirectory,
        DirectoryFilter directoryFilter, FileFilter fileFilter) {
    try {//from   w  w  w  .  j a  v a  2  s .c  o  m
        FTPFile[] allFile = getFtpClient().listFiles(remoteDirectory);
        logger.info("ftp src size={}", allFile.length);
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {

            FTPFile file = allFile[currentFile];
            String name = file.getName();
            if (!file.isDirectory()) {
                if (getFileFilter().accept(name)) {
                    String prefix = null;
                    if (getFtpConfig().getFtpDstNameAppendLocal()) {
                        prefix = localDirectoryPath + remoteDirectory;
                    } else {
                        prefix = localDirectoryPath;
                    }
                    boolean success = false;
                    success = downloadFile(file, prefix, remoteDirectory);
                    int downloadCnt = 1;

                    for (int i = 0; i < 5; i++) {
                        if (success == false) {
                            logger.warn("?!");
                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            login(getIp(), getPort(), getUser(), getPwd());
                            success = downloadFile(file, prefix, remoteDirectory);
                            downloadCnt += 1;
                        } else {
                            break;
                        }
                    }
                    if (downloadCnt > 1 && success == true) {
                        logger.warn("?, {} ", downloadCnt);
                    } else if (downloadCnt > 1 && success == false) {
                        logger.error(", {} ", downloadCnt);
                    }

                } else {
                    logger.error("file suffix {},not include", getFtpConfig().getFileSuffixs());
                    continue;
                }
            } else {
                //directory exclude logic
                if (!getDirectoryFilter().accept(name)) {
                    logger.info("directory exclude name=" + remoteDirectory + " \t regular="
                            + getFtpConfig().getFtpDirectoryExclude());
                    continue;
                }
                if (!getDirectoryInclude().accept(name)) {
                    logger.info("ftp directory {}", name);
                    // create directory if necessary
                    if (!localDirectoryPath.equals(File.separator)) {
                        FileStoreData store = (FileStoreData) FtpConfig.SortTypeClass
                                .valueOf(getFtpConfig().getFtpStoreType().toUpperCase())
                                .getFileStoreTypeClass();
                        if (!store.createDirectory(localDirectoryPath)) {
                            continue;
                        }
                    }
                    downLoadDirectory(localDirectoryPath,
                            (remoteDirectory.equals("/") ? remoteDirectory : (remoteDirectory + File.separator))
                                    + name,
                            directoryFilter, fileFilter);

                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        logger.info("");
        return false;
    }
    return true;
}

From source file:uk.co.nickthecoder.pinkwino.optional.publish.FtpSync.java

private void uploadDirectory(File localDir, String remotePath, int depth) throws IOException {
    // _logger.info( "Syncing directory " + localDir + " -> " + remotePath
    // );/*from  w  w w  . jav a2 s . c  o  m*/

    if (depth >= _maxDepth) {
        // _logger.info( "Max recursion met : " + _maxDepth );
        return;
    }

    _ftp.changeWorkingDirectory(remotePath);

    File[] localFiles = localDir.listFiles();
    FTPFile[] remoteFiles = _ftp.listFiles(remotePath);

    // Iterate over each file in the local directory
    for (int i = 0; i < localFiles.length; i++) {

        File localFile = localFiles[i];

        if (localFile.isFile()) {

            FTPFile remoteFile = findFTPFile(remoteFiles, localFile.getName());

            if (remoteFile == null) {
                uploadFile(localFile);
            } else if (needsUploading(localFile, remoteFile)) {
                _ftp.deleteFile(localFile.getName());
                uploadFile(localFile);
            } else {
            }
        }
    }

    // Iterate over each directory in the local directory
    for (int i = 0; i < localFiles.length; i++) {
        File localFile = localFiles[i];
        if (localFile.isDirectory()) {

            FTPFile remoteFile = findFTPFile(remoteFiles, localFile.getName());

            // If an existing **file** is where a directory needs to be,
            // delete the file.
            if ((remoteFile != null) && (!remoteFile.isDirectory())) {
                _ftp.deleteFile(localFile.getName());
                remoteFile = null;
            }

            String remoteDirectory = remotePath + "/" + localFile.getName();

            // Make the directory if needed
            if (remoteFile == null) {
                _ftp.makeDirectory(remoteDirectory);
            }

            // Recurse
            uploadDirectory(localFile, remoteDirectory, depth + 1);
        }
    }

}