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:it.greenvulcano.util.remotefs.ftp.FTPManager.java

/**
 * @see it.greenvulcano.util.remotefs.RemoteManager#getDir(String, String,
 *      String, java.util.Map)//from  w w w. ja  v a2 s .  c  om
 */
@Override
public boolean getDir(String remoteDirectory, String localParentDirectory, String localDirectory,
        Map<String, String> optProperties) throws RemoteManagerException {
    checkConnected();

    boolean oldAutoConnect = isAutoconnect();
    setAutoconnect(false);

    boolean result = false;
    try {
        changeWorkingDirectory(remoteDirectory);
        String currentlyDownloading = ftpClient.printWorkingDirectory();

        if ((localDirectory == null) || localDirectory.equals("")) {
            localDirectory = new File(remoteDirectory).getName();
        }

        File localDirectoryObj = new File(localParentDirectory, localDirectory);
        if (!localDirectoryObj.exists()) {
            if (!localDirectoryObj.mkdir()) {
                throw new RemoteManagerException(
                        "Cannot create local directory " + localDirectoryObj.getAbsolutePath());
            }
            logger.debug("Local directory " + localDirectoryObj.getAbsolutePath() + " created");
        }

        FTPFile[] results = ftpClient.listFiles();

        if (results != null) {
            for (FTPFile currFTPFile : results) {
                if (currFTPFile != null) {
                    boolean partialResult = true;
                    if (currFTPFile.isDirectory()) {
                        partialResult = getDir(currFTPFile.getName(), localDirectoryObj.getAbsolutePath(), null,
                                optProperties);
                    } else {
                        partialResult = get(null, currFTPFile.getName(), localDirectoryObj.getAbsolutePath(),
                                null, optProperties);
                    }
                    if (!partialResult) {
                        break;
                    }
                } else {
                    logger.debug("Remote file entry NULL");
                }
            }
        }

        ftpClient.changeToParentDirectory();

        int reply = ftpClient.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            logger.debug("Remote directory " + currentlyDownloading + " downloaded");
            result = true;
        } else {
            logger.warn("Could not download remote directory " + currentlyDownloading
                    + " (FTP Server NEGATIVE response):");
            logServerReply(Level.WARN);
        }
        return result;
    } catch (RemoteManagerException exc) {
        throw exc;
    } catch (IOException exc) {
        throw new RemoteManagerException("I/O error", exc);
    } catch (Exception exc) {
        throw new RemoteManagerException("Generic error", exc);
    } finally {
        setAutoconnect(oldAutoConnect);
        if (isAutoconnect()) {
            disconnect();
        }
    }
}

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

/**
 * @see it.greenvulcano.util.remotefs.RemoteManager#rm(String, String, java.util.Map)
 *///from  www .  j  a v a2s .c  om
@Override
public boolean rm(String remoteDirectory, String entryNamePattern, Map<String, String> optProperties)
        throws RemoteManagerException {
    checkConnected();

    boolean oldAutoConnect = isAutoconnect();
    setAutoconnect(false);

    boolean result = false;
    try {
        if (remoteDirectory != null) {
            changeWorkingDirectory(remoteDirectory);
        }

        String[] filenames = ftpClient.listNames();
        int detectedFiles = (filenames != null ? filenames.length : 0);
        FTPFile[] results = ftpClient.listFiles();
        int parsedFiles = (results != null ? results.length : 0);
        if (detectedFiles != parsedFiles) {
            logger.warn("Some of all of the detected (" + detectedFiles + ") file entries couldn't be parsed ("
                    + parsedFiles + "), recursive delete may fail");
        }

        if (results != null) {
            RegExFileFilter fileFilter = new RegExFileFilter(entryNamePattern, RegExFileFilter.ALL, -1);
            for (FTPFile currFTPFile : results) {
                if (currFTPFile != null) {
                    if (fileFilter.accept(currFTPFile)) {
                        if (currFTPFile.isDirectory()) {
                            result = rm(currFTPFile.getName(), ".*", optProperties); // remove all sub-directory content
                            ftpClient.changeToParentDirectory();
                            if (result) {
                                ftpClient.removeDirectory(currFTPFile.getName());
                                int reply = ftpClient.getReplyCode();
                                if (FTPReply.isPositiveCompletion(reply)) {
                                    logger.debug("Remote directory " + currFTPFile.getName() + " deleted.");
                                    result = true;
                                } else {
                                    logger.warn("FTP Server NEGATIVE response: ");
                                    logServerReply(Level.WARN);
                                }
                            }
                        } else {
                            ftpClient.deleteFile(currFTPFile.getName());
                            int reply = ftpClient.getReplyCode();
                            if (FTPReply.isPositiveCompletion(reply)) {
                                logger.debug("Remote file " + currFTPFile.getName() + " deleted.");
                                result = true;
                            } else {
                                logger.warn("FTP Server NEGATIVE response: ");
                                logServerReply(Level.WARN);
                            }
                        }

                        if (!result) {
                            break;
                        }
                    }
                }
            }
        }
        return result;
    } catch (IOException exc) {
        throw new RemoteManagerException("I/O error", exc);
    } catch (Exception exc) {
        throw new RemoteManagerException("Generic error", exc);
    } finally {
        setAutoconnect(oldAutoConnect);
        if (isAutoconnect()) {
            disconnect();
        }
    }
}

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

/**
 * @see it.greenvulcano.util.remotefs.RemoteManager#get(String, String,
 *      String, java.util.Map)//from   w  w w .ja  v  a  2 s. c  o  m
 */
@Override
public boolean get(String remoteDirectory, String remoteFilePattern, String localDirectory,
        Map<String, String> optProperties) throws RemoteManagerException {
    checkConnected();

    boolean oldAutoConnect = isAutoconnect();
    setAutoconnect(false);

    boolean result = false;
    try {
        changeWorkingDirectory(remoteDirectory);
        String currentlyDownloading = ftpClient.printWorkingDirectory();

        File localDirectoryObj = new File(localDirectory);
        if (!localDirectoryObj.exists()) {
            if (!localDirectoryObj.mkdir()) {
                throw new RemoteManagerException(
                        "Cannot create local directory " + localDirectoryObj.getAbsolutePath());
            }
            logger.debug("Local directory " + localDirectoryObj.getAbsolutePath() + " created");
        }

        FTPFile[] results = ftpClient.listFiles();

        if (results != null) {
            RegExFileFilter fileFilter = new RegExFileFilter(remoteFilePattern, RegExFileFilter.ALL, -1);
            for (FTPFile currFTPFile : results) {
                if (currFTPFile != null) {
                    if (fileFilter.accept(currFTPFile)) {
                        boolean partialResult = true;
                        if (currFTPFile.isDirectory()) {
                            partialResult = getDir(currFTPFile.getName(), localDirectoryObj.getAbsolutePath(),
                                    null, optProperties);
                        } else {
                            partialResult = get(null, currFTPFile.getName(),
                                    localDirectoryObj.getAbsolutePath(), null, optProperties);
                        }
                        if (!partialResult) {
                            break;
                        }
                    }
                } else {
                    logger.debug("Remote file entry NULL");
                }
            }
        }

        int reply = ftpClient.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            logger.debug("Remote directory " + currentlyDownloading + " downloaded");
            result = true;
        } else {
            logger.warn("Could not download remote directory " + currentlyDownloading
                    + " (FTP Server NEGATIVE response):");
            logServerReply(Level.WARN);
        }
        return result;
    } catch (RemoteManagerException exc) {
        throw exc;
    } catch (IOException exc) {
        throw new RemoteManagerException("I/O error", exc);
    } catch (Exception exc) {
        throw new RemoteManagerException("Generic error", exc);
    } finally {
        setAutoconnect(oldAutoConnect);
        if (isAutoconnect()) {
            disconnect();
        }
    }
}

From source file:ConnectionInfo.java

private void dragNDropSupport() {
    // --- Drag source ---

    //  Allows text to be moved only.
    int operations = DND.DROP_COPY | DND.DROP_MOVE;
    final DragSource dragSource = new DragSource(remoteDirBrowser.getControl(), operations);

    // Data should be transfered in plain text format.
    Transfer[] formats = new Transfer[] { TextTransfer.getInstance() };
    dragSource.setTransfer(formats);/*ww  w  .  j a  v a2s. co m*/

    dragSource.addDragListener(new DragSourceListener() {
        public void dragStart(DragSourceEvent event) {
            System.out.println("DND starts");
            // disallows DND if no remote file is selected.
            IStructuredSelection selection = (IStructuredSelection) remoteDirBrowser.getSelection();
            FTPFile file = (FTPFile) selection.getFirstElement();
            if (file == null || file.isDirectory()) {
                event.doit = false;
            }
        }

        public void dragSetData(DragSourceEvent event) {
            // Provides the text data.
            if (TextTransfer.getInstance().isSupportedType(event.dataType)) {
                IStructuredSelection selection = (IStructuredSelection) remoteDirBrowser.getSelection();
                FTPFile file = (FTPFile) selection.getFirstElement();
                if (file == null || file.isDirectory()) {
                    event.doit = false;
                } else {
                    event.data = file.getName();
                }
            }
        }

        public void dragFinished(DragSourceEvent event) {
        }
    });

    remoteDirBrowser.getControl().addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent e) {
            dragSource.dispose();
        }
    });

    // --- Drop target ---
    final DropTarget dropTarget = new DropTarget(localDirBrowser.getControl(), operations);

    dropTarget.setTransfer(formats);

    dropTarget.addDropListener(new DropTargetListener() {
        public void dragEnter(DropTargetEvent event) {
        }

        public void dragLeave(DropTargetEvent event) {
        }

        public void dragOperationChanged(DropTargetEvent event) {
        }

        public void dragOver(DropTargetEvent event) {
        }

        public void drop(DropTargetEvent event) {
            if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
                String text = (String) event.data;
                File target = new File((File) localDirBrowser.getInput(), text);
                if (target.exists()) {
                    if (!MessageDialog.openConfirm(getShell(), "Overwriting confirmation",
                            "Overwrite file " + target + "?")) {
                        return;
                    }
                }

                try {
                    FileOutputStream stream = new FileOutputStream(target);

                    if (ftp.retrieveFile(text, stream)) {
                        logMessage("File retrieved successfully.", true);
                        // refreshes the file list.
                        localDirBrowser.refresh();
                    } else {
                        logError("Failed to retrieve file: " + text);
                    }

                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public void dropAccept(DropTargetEvent event) {
        }
    });

    localDirBrowser.getControl().addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent e) {
            dropTarget.dispose();
        }
    });
}

From source file:com.sos.VirtualFileSystem.FTP.SOSVfsFtpBaseClass.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 .  j  a va  2 s  .c o 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 strCurrentDirectory = null;
    // TODO vecDirectoryListing = null; prfen, ob notwendig
    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;
        }
        FTPFile[] objFTPFileList = null;
        try {
            objFTPFileList = Client().listFiles(lstrPathName);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        //         if (1 == 1) {
        //            try {
        //               fileList = listNames(lstrPathName);
        //               // fileList = listNames(pstrPathName);
        //            }
        //            catch (IOException e) {
        //               e.printStackTrace(System.err);
        //            }
        //         }
        // else {
        // FTPFile[] objFtpFiles = Client().listFiles(lstrPathName);
        // if (objFtpFiles != null) {
        // int i = 0;
        // for (FTPFile ftpFile : objFtpFiles) {
        // fileList[i++] = ftpFile.getName();
        // }
        // }
        // }
        if (objFTPFileList == null) {
            return vecDirectoryListing;
        }
        for (FTPFile ftpFile : objFTPFileList) {
            String strCurrentFile = ftpFile.getName();
            if (isNotHiddenFile(strCurrentFile)) {
                if (flgRecurseSubFolders == false && ftpFile.isFile()) {
                    if (strCurrentFile.startsWith(strCurrentDirectory) == false)
                        strCurrentFile = strCurrentDirectory + "/" + strCurrentFile;
                    vecDirectoryListing.add(strCurrentFile);
                } else {
                    //                  DoCD(strCurrentFile); // is this file-entry a subfolder?
                    //                  if (isNegativeCommandCompletion()) {
                    if (ftpFile.isFile()) {
                        if (strCurrentFile.startsWith(strCurrentDirectory) == false)
                            strCurrentFile = strCurrentDirectory + "/" + strCurrentFile;
                        vecDirectoryListing.add(strCurrentFile);
                    } else {
                        //                     DoCD(strCurrentDirectory);
                        if (ftpFile.isDirectory() && flgRecurseSubFolders) {
                            Vector<String> vecNames = getFilenames(strCurrentFile);
                            if (vecNames != null) {
                                vecDirectoryListing.addAll(vecNames);
                            }
                        }
                    }
                }
            }
        }
    }
    logger.debug(SOSVfs_I_126.params(strCurrentDirectory));
    if (strCurrentDirectory != null) {
        DoCD(strCurrentDirectory);
        DoPWD();
    }
    return vecDirectoryListing;
}

From source file:com.guardtrax.ui.screens.HomeScreen.java

private boolean existsftpServer(FTPFile[] ftpFiles, String testFile) {
    for (FTPFile ftpFile : ftpFiles) {
        if (ftpFile.getName().equalsIgnoreCase(testFile))
            return true;
    }//from  w w w  . j  av  a 2s  . c om
    return false;
}

From source file:nl.esciencecenter.xenon.adaptors.filesystems.ftp.FtpFileSystem.java

private FTPFile findFTPFile(FTPFile[] files, Path path) throws NoSuchPathException {

    if (files == null || files.length == 0) {
        throw new NoSuchPathException(ADAPTOR_NAME, "Path not found: " + path);
    }//from   w  w w .  j av a 2s  . co m

    String name = path.getFileNameAsString();

    for (FTPFile f : files) {

        if (f != null && f.getName().equals(name)) {
            return f;
        }
    }

    throw new NoSuchPathException(ADAPTOR_NAME, "Path not found: " + path);
}

From source file:nl.esciencecenter.xenon.adaptors.filesystems.ftp.FtpFileSystem.java

@Override
protected List<PathAttributes> listDirectory(Path path) throws XenonException {
    assertIsOpen();//from ww  w . j  av a  2 s  .c  o m
    assertDirectoryExists(path);

    try {
        ArrayList<PathAttributes> result = new ArrayList<>();

        for (FTPFile f : ftpClient.listFiles(path.toString(), FTPFileFilters.NON_NULL)) {
            result.add(convertAttributes(path.resolve(f.getName()), f));
        }

        return result;
    } catch (IOException e) {
        throw new XenonException(ADAPTOR_NAME, "Failed to retrieve directory listing of " + path, e);
    }
}

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

@Override
public boolean exists(FTPFile f) throws FileSystemException {
    try {//from w  ww .  ja  v a2s .  c  om
        FTPFile[] files = ftpClient.listFiles();
        for (FTPFile o : files) {
            if (o.isDirectory()) {
                if ((f.getName().endsWith("/") ? o.getName() + "/" : o.getName()).equals(f.getName())) {
                    return true;
                }
            } else if (o.getName().equals(f.getName())) {
                return true;
            }
        }
    } catch (IOException e) {
        throw new FileSystemException(e);
    }
    return false;
}

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

@Override
public OutputStream createFile(FTPFile f) throws FileSystemException, IOException {
    OutputStream outputStream = ftpClient.storeFileStream(f.getName());
    return completePendingCommand(outputStream);
}