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:com.claim.support.FtpUtil.java

public void uploadMutiFileWithFTP(String targetDirectory, FileTransferController fileTransferController) {
    try {/*from   ww w . j  a v a 2  s  . c o m*/
        FtpProperties properties = new ResourcesProperties().loadFTPProperties();

        FTPClient ftp = new FTPClient();
        ftp.connect(properties.getFtp_server());
        if (!ftp.login(properties.getFtp_username(), properties.getFtp_password())) {
            ftp.logout();
        }
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }
        ftp.enterLocalPassiveMode();
        System.out.println("Remote system is " + ftp.getSystemName());
        ftp.changeWorkingDirectory(targetDirectory);
        System.out.println("Current directory is " + ftp.printWorkingDirectory());
        FTPFile[] ftpFiles = ftp.listFiles();
        if (ftpFiles != null && ftpFiles.length > 0) {
            for (FTPFile file : ftpFiles) {
                if (!file.isFile()) {
                    continue;
                }
                System.out.println("File is " + file.getName());
                OutputStream output;
                output = new FileOutputStream(
                        properties.getFtp_remote_directory() + File.separator + file.getName());
                ftp.retrieveFile(file.getName(), output);
                output.close();
            }
        }
        ftp.logout();
        ftp.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

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 {//from w  w  w  .ja v a 2  s . c  om
            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:dk.dma.dmiweather.service.FTPLoader.java

/**
 * Copied the files from DMIs ftp server to the local machine
 *
 * @return a Map with a local file and the time the file was created on the FTP server
 *///w  w  w.  j  a  v  a 2s  . c om
private Map<File, Instant> transferFilesIfNeeded(FTPClient client, String directoryName, List<FTPFile> files)
        throws IOException {

    File current = new File(tempDirLocation, directoryName);
    if (newestDirectories.isEmpty()) {
        // If we just started check if there is data from an earlier run and delete it
        File temp = new File(tempDirLocation);
        if (temp.exists()) {
            File[] oldFolders = temp.listFiles(new PatternFilenameFilter(FOLDER_PATTERN));
            if (oldFolders != null) {
                List<File> foldersToDelete = Lists.newArrayList(oldFolders);
                foldersToDelete.remove(current);
                for (File oldFolder : foldersToDelete) {
                    log.info("deleting old GRIB folder {}", oldFolder);
                    deleteRecursively(oldFolder);
                }
            }
        }
    }

    if (!current.exists()) {
        if (!current.mkdirs()) {
            throw new IOException("Unable to create temp directory " + current.getAbsolutePath());
        }
    }

    Stopwatch stopwatch = Stopwatch.createStarted();
    Map<File, Instant> transferred = new HashMap<>();
    for (FTPFile file : files) {
        File tmp = new File(current, file.getName());
        if (tmp.exists()) {
            long localSize = Files.size(tmp.toPath());
            if (localSize != file.getSize()) {
                log.info("deleting {} local file has size {}, remote is {}", tmp.getName(), localSize,
                        file.getSize());
                if (!tmp.delete()) {
                    log.warn("Unable to delete " + tmp.getAbsolutePath());
                }
            } else {
                // If the file has the right size we assume it was copied correctly (otherwise we needed to hash them)
                log.info("Reusing already downloaded version of {}", tmp.getName());
                transferred.put(tmp, file.getTimestamp().toInstant());
                continue;
            }
        }
        if (tmp.createNewFile()) {
            log.info("downloading {}", tmp.getName());

            // this often fails with java.net.ConnectException: Operation timed out
            int count = 0;
            while (count++ < MAX_TRIES) {
                try (FileOutputStream fout = new FileOutputStream(tmp)) {
                    client.retrieveFile(file.getName(), fout);
                    fout.flush();
                    break;
                } catch (IOException e) {
                    log.warn(String.format("Failed to transfer file %s, try number %s", file.getName(), count),
                            e);
                }
            }
        } else {
            throw new IOException("Unable to create temp file on disk.");
        }

        transferred.put(tmp, file.getTimestamp().toInstant());
    }
    log.info("transferred weather files in {} ms", stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
    return transferred;
}

From source file:com.stacksync.desktop.connection.plugins.ftp.FtpTransferManager.java

public Map<String, RemoteFile> getDirectoryList(String folderPath) throws StorageException {

    try {/*ww  w.ja  v a 2  s.  co m*/
        Map<String, RemoteFile> files = new HashMap<String, RemoteFile>();
        FTPFile[] ftpFiles = ftp.listFiles(getConnection().getPath() + "/" + folderPath);

        for (FTPFile f : ftpFiles) {
            files.put(folderPath + "/" + f.getName(),
                    new RemoteFile(folderPath + "/" + f.getName(), f.getSize(), f));
            if (f.isDirectory()) {
                files.putAll(getDirectoryList(folderPath + "/" + f.getName()));
            }
        }

        return files;
    } catch (IOException ex) {
        logger.error("Unable to list FTP directory.", ex);
        throw new StorageException(ex);
    }
}

From source file:de.thischwa.pmcms.tool.connection.ftp.FtpTransfer.java

/**
 * Searches a FTPFile by name from an array of FTPFiles.
 * //from w  w w  .j a  va2 s . com
 * @return FTPClient, if exists, or null.
 */
private FTPFile getByName(final FTPFile[] files, final String name) {
    if (StringUtils.isBlank(name))
        return null;
    for (FTPFile file : files)
        if (file.getName().equals(name))
            return file;
    return null;
}

From source file:com.example.lista3new.SyncService.java

private void syncFiles(final String ftpDir, final String localDir) {
    Log.d(TAG, "Curr:" + ftpGetCurrentDirectory() + ":" + ftpDir + "|");
    File dir = new File(localDir);
    if (!dir.exists()) {
        dir.mkdirs();//from   ww w.j  av  a2 s. co  m
    }
    if (!ftpGetCurrentDirectory().equals(ftpDir)) {
        ftpChangeDirectory(ftpDir);
    }
    Log.d(TAG, "ftpDir: " + ftpDir);
    Log.d(TAG, "localDir: " + localDir);
    List<FTPFile> ftpFiles = ftpGetFileList(ftpDir);
    List<File> localFiles = getLocalFileList(localDir);
    for (int i = 0; i < ftpFiles.size(); ++i) {
        FTPFile file = ftpFiles.get(i);
        String fileName = file.getName();
        File localFile = new File(localDir + "/" + fileName);
        if (file.isFile()) {
            Log.d(TAG, "file: " + fileName);
            if (!localFile.exists()) {
                ftpDownloadFile(ftpDir + "/" + fileName, localDir + "/" + fileName);
                sendFileDownloadedMessage(localDir, fileName, FILE_TYPE);
            }

        } else if (file.isDirectory() && !fileName.equals(".") && !fileName.equals("..")) {
            boolean addToList = !localFile.exists();
            Log.d(TAG, "dir: " + fileName);
            syncFiles(ftpDir + "/" + file.getName(), localDir + "/" + file.getName());
            if (addToList) {
                sendFileDownloadedMessage(localDir, fileName, DIR_TYPE);
            }
        }

    }
    for (int i = 0; i < localFiles.size(); ++i) {
        File file = localFiles.get(i);
        String fileName = file.getName();
        Log.d(TAG, "Found local file:" + localDir + "/" + file.getName());
        if (file.isFile() && !ftpFileExists(ftpDir + "/" + fileName)) {
            Log.d(TAG, "Uploading to: " + ftpDir + "/" + file.getName());
            ftpUpload(localDir + "/" + file.getName(), ftpDir + "/" + file.getName());
        } else if (file.isDirectory() && !ftpDirExists(ftpDir + "/" + fileName)) {
            ftpMakeDirectory(ftpDir + "/" + file.getName());
            // synFiles
        }

    }

}

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

private void delete(final FTPFile ftpFile) throws IOException {
    if (ftpFile == null)
        throw new BapPublisherException(Messages.exception_client_fileIsNull());
    final String entryName = ftpFile.getName();
    if (".".equals(entryName) || "..".equals(entryName))
        return;//from  w w  w  .  j a va 2  s.  c om
    if (ftpFile.isDirectory()) {
        if (!changeDirectory(entryName))
            throw new BapPublisherException(Messages.exception_cwdException(entryName));
        delete();
        if (!ftpClient.changeToParentDirectory())
            throw new BapPublisherException(Messages.exception_client_cdup());
        if (!ftpClient.removeDirectory(entryName))
            throw new BapPublisherException(Messages.exception_client_rmdir(entryName));
    } else {
        if (!ftpClient.deleteFile(entryName))
            throw new BapPublisherException(Messages.exception_client_dele(entryName));
    }
}

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  v a  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:net.seedboxer.camel.component.file.remote.ftp2.Ftp2Operations.java

protected Long getSize(String targetName) {
    List<FTPFile> listFiles = listFiles();
    for (FTPFile ftpFile : listFiles) {
        if (targetName.equals(ftpFile.getName())) {
            return ftpFile.getSize();
        }/*from  w  ww  . j av a  2s  . c  om*/
    }
    return null;
}

From source file:com.unispezi.cpanelremotebackup.CPanelRemoteBackup.java

/**
 * Looks for the youngest backup which is on the server
 *
 * @param fileNamePattern pattern to recognize backups
 * @return file name of youngest backup file
 *///from  www .j  av a2  s  .  c  o m
private String findYoungestBackup(Pattern fileNamePattern) {
    List<FTPFile> files = ftp.listFilesInDirectory("/");
    FTPFile youngest = null;

    for (FTPFile file : files) {
        if (fileNamePattern.matcher(file.getName()).matches()) {
            if ((youngest == null) || (youngest.getTimestamp().before(file.getTimestamp()))) {
                youngest = file;
            }
        }
    }
    if (youngest != null) {
        return youngest.getName();
    } else {
        return null;
    }
}