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.savy3.util.MainframeFTPClientUtils.java

public static List<String> listSequentialDatasets(String pdsName, Configuration conf) throws IOException {
    List<String> datasets = new ArrayList<String>();
    FTPClient ftp = null;/*  w w  w.  j a  v a2 s.  c  o  m*/
    try {
        ftp = getFTPConnection(conf);
        if (ftp != null) {
            ftp.changeWorkingDirectory("'" + pdsName + "'");
            FTPFile[] ftpFiles = ftp.listFiles();
            for (FTPFile f : ftpFiles) {
                if (f.getType() == FTPFile.FILE_TYPE) {
                    datasets.add(f.getName());
                }
            }
        }
    } catch (IOException ioe) {
        throw new IOException("Could not list datasets from " + pdsName + ":" + ioe.toString());
    } finally {
        if (ftp != null) {
            closeFTPConnection(ftp);
        }
    }
    return datasets;
}

From source file:joshuatee.wx.UtilityFTP.java

public static String[] GetNidsArr(Context c, String url, String path, String frame_cnt_str) {

    int frame_cnt = Integer.parseInt(frame_cnt_str);
    String[] nids_arr = new String[frame_cnt];

    try {/*w  w w.  j  av  a 2  s . c om*/
        FTPClient ftp = new FTPClient();

        //String user = "ftp";
        //String pass = "anonymous";

        ftp.connect(url);

        if (!ftp.login("ftp", "anonymous")) {
            ftp.logout();
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }

        ftp.enterLocalPassiveMode();
        ftp.changeWorkingDirectory(path);
        //reply = ftp.getReplyCode();

        FTPFile[] ftpFiles = ftp.listFiles();

        //get newest .xml file name from ftp server
        java.util.Date lastMod = ftpFiles[0].getTimestamp().getTime();
        FTPFile choice = ftpFiles[0];

        for (FTPFile file : ftpFiles) {
            if (file.getTimestamp().getTime().after(lastMod) && !file.getName().equals("sn.last")) {
                choice = file;
                lastMod = file.getTimestamp().getTime();
            }
        }

        int seq = Integer.parseInt(choice.getName().replace("sn.", "")); // was ALl
        int j = 0;
        int k = seq - frame_cnt + 1;
        for (j = 0; j < frame_cnt; j++) {
            // files range from 0000 to 0250, if num is negative add 251
            int tmp_k = k;

            if (tmp_k < 0)
                tmp_k = tmp_k + 251;

            nids_arr[j] = "sn." + String.format("%4s", Integer.toString(tmp_k)).replace(' ', '0');
            k++;
        }

        FileOutputStream fos;
        for (j = 0; j < frame_cnt; j++) {
            fos = c.openFileOutput(nids_arr[j], Context.MODE_PRIVATE);
            ftp.retrieveFile(nids_arr[j], fos);
            fos.close();
        }

        ftp.logout();
        ftp.disconnect();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return nids_arr;

}

From source file:com.hdfstoftp.main.HdfsToFtp.java

/**
 * ??Map/*from   w w  w  .jav a  2  s .  c om*/
 * 
 * @param path
 * @return Map<String, String>
 * @throws Exception
 * @throws IllegalStateException
 * @throws NoSuchElementException
 */
public static Map<String, String> getFileNameMap(String path, FTPClientPool ftpPool)
        throws NoSuchElementException, IllegalStateException, Exception {
    Map<String, String> fileNameMap = new HashMap<String, String>();
    FTPClient client = ftpPool.borrowObject();
    FTPFile[] files = client.listFiles(path);
    ftpPool.returnObject(client);
    for (FTPFile file : files) {
        if (file.isFile()) {
            fileNameMap.put(file.getName(), "");
        }
    }
    return fileNameMap;
}

From source file:main.TestManager.java

/**
 * Deletes all files on the server and uploads all the
 * tests from the local directory./*  ww w .ja va2  s . co m*/
 */
public static void syncServerWithTest() {
    FTPClient ftp = new FTPClient();
    boolean error = false;
    try {
        int reply;
        String server = "zajicek.endora.cz";
        ftp.connect(server, 21);

        // After connection attempt, we check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        //Not connected successfully - inform the user
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            Debugger.println("FTP server refused connection.");
            ErrorInformer.failedSyncing();
            return;
        }
        // LOGIN
        boolean success = ftp.login("plakato", "L13nK4");
        Debugger.println("Login successful: " + success);
        if (success == false) {
            ftp.disconnect();
            ErrorInformer.failedSyncing();
            return;
        }
        ftp.enterLocalPassiveMode();
        // Get all files from the server
        FTPFile[] files = ftp.listFiles();
        System.out.println("Got files! Count: " + files.length);
        // Delete all current tests on the server to be replaced with 
        // actualized version from local directory
        for (FTPFile f : files) {
            if (f.getName() == "." || f.getName() == "..") {
                continue;
            }
            if (f.isFile()) {
                ftp.deleteFile(f.getName());
            }
        }
        // Copy the files from local folder to server
        File localFolder = new File("src/tests/");
        File[] localFiles = localFolder.listFiles();
        int failed = 0;
        for (File f : localFiles) {
            if (f.getName() == "." || f.getName() == "..") {
                continue;
            }
            if (f.isFile()) {
                Debugger.println(f.getName());
                File file = new File("src/tests/" + f.getName());
                InputStream input = new FileInputStream(file);
                if (!ftp.storeFile(f.getName(), input))
                    failed++;
                input.close();
            }
        }
        // If we failed to upload some file, inform the user
        if (failed != 0) {
            ftp.disconnect();
            ErrorInformer.failedSyncing();
            return;
        }
        // Disconnect ftp client or resolve the potential error
        ftp.logout();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
        if (error) {
            ErrorInformer.failedSyncing();
            return;
        }
    }
    Alert alert = new Alert(AlertType.INFORMATION);
    alert.setTitle("Upload hotov");
    alert.setHeaderText(null);
    alert.setContentText("spene sa podarilo skoprova vetky testy na server!");

    alert.showAndWait();
    alert.close();
}

From source file:com.ephesoft.dcma.util.FTPUtil.java

/**
 * API to download files from an arbitrary directory hierarchy on the remote ftp server
 * //from ww w  .  j  a  v  a 2 s.c om
 * @param client {@link FTPClient}
 * @param ftpDirectory{{@link String} the directory tree only delimited with / chars. No file name!
 * @param destDirectoryPath {@link String} the path where file will be downloaded.
 * @throws Exception
 */
public static void retrieveFiles(final FTPClient client, final String ftpDirectory,
        final String destDirectoryPath) throws IOException {
    boolean dirExists = true;
    String[] directories = ftpDirectory.split(DIRECTORY_SEPARATOR);
    for (String dir : directories) {
        if (!dir.isEmpty()) {
            if (dirExists) {
                dirExists = client.changeWorkingDirectory(dir);
            }
        }
    }
    FTPFile[] fileList = client.listFiles();
    if (fileList != null && fileList.length > 0) {
        String outputFilePath;
        FileOutputStream fileOutputStream;
        for (FTPFile file : fileList) {
            outputFilePath = EphesoftStringUtil.concatenate(destDirectoryPath, File.separator, file.getName());
            fileOutputStream = new FileOutputStream(outputFilePath);
            client.retrieveFile(file.getName(), fileOutputStream);
            fileOutputStream.close();
        }
    }
}

From source file:com.ephesoft.dcma.util.FTPUtil.java

/**
 * API for deleting the data existing in ftp directory on the ftp server.
 * //  www . j a v  a  2s  .  com
 * @param client {@link FTPClient}
 * @param ftpDirectory {@link String}
 * @param isSourceFolderDeleted
 */
public static void deleteExistingFTPData(final FTPClient client, final String ftpDirectory,
        final boolean isSourceFolderDeleted) {
    if (client != null && ftpDirectory != null) {
        try {
            FTPFile[] ftpFileList = client.listFiles(ftpDirectory);
            for (FTPFile ftpFile : ftpFileList) {
                client.deleteFile(
                        EphesoftStringUtil.concatenate(ftpDirectory, File.separator, ftpFile.getName()));
            }
            if (isSourceFolderDeleted) {
                client.removeDirectory(ftpDirectory);
            }
        } catch (IOException e) {
            LOGGER.error(EphesoftStringUtil.concatenate("Error in deleting existing file on ftp server ",
                    e.getMessage(), e));
        }
    }
}

From source file:madkitgroupextension.export.Export.java

private static void sendToWebSite() throws IOException {
    System.out.println("Enter your password :");
    byte b[] = new byte[100];
    int l = System.in.read(b);
    String pwd = new String(b, 0, l);

    boolean reconnect = true;
    long time = System.currentTimeMillis();
    File current_file_transfert = null;
    File current_directory_transfert = null;

    while (reconnect) {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(FTPURL, 21);//from w w w  . j  a  va 2 s .  com
        try {
            if (ftpClient.isConnected()) {
                System.out.println("Connected to server " + FTPURL + " (Port: " + FTPPORT + ") !");
                if (ftpClient.login(FTPLOGIN, pwd)) {
                    ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
                    System.out.println("Logged as " + FTPLOGIN + " !");
                    System.out.print("Updating...");

                    FTPFile files[] = ftpClient.listFiles("");
                    FTPFile downloadroot = null;
                    FTPFile docroot = null;

                    for (FTPFile f : files) {
                        if (f.getName().equals("downloads")) {
                            downloadroot = f;
                            if (docroot != null)
                                break;
                        }
                        if (f.getName().equals("doc")) {
                            docroot = f;
                            if (downloadroot != null)
                                break;
                        }
                    }
                    if (downloadroot == null) {
                        //ftpClient.changeWorkingDirectory("/");
                        if (!ftpClient.makeDirectory("downloads")) {
                            System.err.println("Impossible to create directory: downloads");
                        }
                    }
                    if (docroot == null) {
                        //ftpClient.changeWorkingDirectory("/");
                        if (!ftpClient.makeDirectory("doc")) {
                            System.err.println("Impossible to create directory: doc");
                        }
                    }

                    updateFTP(ftpClient, "downloads/", new File(ExportPathFinal), current_file_transfert,
                            current_directory_transfert);
                    updateFTP(ftpClient, "doc/", new File("./doc"), current_file_transfert,
                            current_directory_transfert);
                    reconnect = false;

                    System.out.println("[OK]");
                    if (ftpClient.logout()) {
                        System.out.println("Logged out from " + FTPLOGIN + " succesfull !");
                    } else
                        System.err.println("Logged out from " + FTPLOGIN + " FAILED !");
                } else
                    System.err.println("Impossible to log as " + FTPLOGIN + " !");

                ftpClient.disconnect();
                System.out.println("Disconnected from " + FTPURL + " !");
            } else {
                System.err.println("Impossible to get a connection to the server " + FTPURL + " !");
            }
            reconnect = false;
        } catch (TransfertException e) {
            if (System.currentTimeMillis() - time > 30000) {
                System.err.println("A problem occured during the transfert...");
                System.out.println("Reconnection in progress...");
                try {
                    ftpClient.disconnect();
                } catch (Exception e2) {
                }
                current_file_transfert = e.current_file_transfert;
                current_directory_transfert = e.current_directory_transfert;
                time = System.currentTimeMillis();
            } else {
                System.err.println("A problem occured during the transfert. Transfert aborded.");
                throw e.original_exception;
            }
        }
    }
}

From source file:com.seajas.search.contender.service.modifier.ArchiveModifierService.java

/**
 * Recursively retrieve a directory listing from the FTP server.
 * /*from   w  ww . ja  v a  2s .com*/
 * @param path
 * @param ftpClient
 * @param exclusionExpression
 * @return List<FTPFile>
 * @throws IOException
 */
private static List<ArchiveFile> retrieveFiles(final String path, final FTPClient ftpClient,
        final String exclusionExpression) throws IOException {
    List<FTPFile> files = Arrays.asList(ftpClient.listFiles(path));
    List<ArchiveFile> result = new Vector<ArchiveFile>();

    for (FTPFile file : files)
        if (!file.getName().equals(".") && !file.getName().equals("..")) {
            if (file.isDirectory()) {
                String folderPath = path + (path.endsWith("/") ? "" : "/") + file.getName();

                if (!StringUtils.hasText(exclusionExpression) || !folderPath.matches(exclusionExpression))
                    result.addAll(retrieveFiles(folderPath, ftpClient, exclusionExpression));
            } else if (file.isFile() && (!StringUtils.hasText(exclusionExpression)
                    || !(path + "/" + file.getName()).matches(exclusionExpression)))
                result.add(new ArchiveFile(path, file));
        }

    return result;
}

From source file:madkitgroupextension.export.Export.java

public static void updateFTP(FTPClient ftpClient, String _directory_dst, File _directory_src,
        File _current_file_transfert) throws IOException, TransfertException {
    ftpClient.changeWorkingDirectory("./");
    FTPListParseEngine ftplpe = ftpClient.initiateListParsing(_directory_dst);
    FTPFile files[] = ftplpe.getFiles();

    File current_file_transfert = _current_file_transfert;

    try {/*from   w  w w . j  a  v a 2 s.co m*/
        for (File f : _directory_src.listFiles()) {
            if (f.isDirectory()) {
                if (!f.getName().equals("./") && !f.getName().equals("../")) {
                    if (_current_file_transfert != null) {
                        if (!_current_file_transfert.getCanonicalPath().startsWith(f.getCanonicalPath()))
                            continue;
                        else
                            _current_file_transfert = null;
                    }
                    boolean found = false;
                    for (FTPFile ff : files) {
                        if (f.getName().equals(ff.getName())) {
                            if (ff.isFile()) {
                                ftpClient.deleteFile(_directory_dst + ff.getName());
                            } else
                                found = true;
                            break;
                        }
                    }

                    if (!found) {
                        ftpClient.changeWorkingDirectory("./");
                        if (!ftpClient.makeDirectory(_directory_dst + f.getName() + "/"))
                            System.err.println(
                                    "Impossible to create directory " + _directory_dst + f.getName() + "/");
                    }
                    updateFTP(ftpClient, _directory_dst + f.getName() + "/", f, _current_file_transfert);
                }
            } else {
                if (_current_file_transfert != null) {
                    if (!_current_file_transfert.equals(f.getCanonicalPath()))
                        continue;
                    else
                        _current_file_transfert = null;
                }
                current_file_transfert = _current_file_transfert;
                FTPFile found = null;
                for (FTPFile ff : files) {
                    if (f.getName().equals(ff.getName())) {
                        if (ff.isDirectory()) {
                            FileTools.removeDirectory(ftpClient, _directory_dst + ff.getName());
                        } else
                            found = ff;
                        break;
                    }
                }
                if (found == null || (found.getTimestamp().getTimeInMillis() - f.lastModified()) < 0
                        || found.getSize() != f.length()) {
                    FileInputStream fis = new FileInputStream(f);
                    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                    if (!ftpClient.storeFile(_directory_dst + f.getName(), fis))
                        System.err.println("Impossible to send file: " + _directory_dst + f.getName());
                    fis.close();
                    for (FTPFile ff : ftplpe.getFiles()) {
                        if (f.getName().equals(ff.getName())) {
                            f.setLastModified(ff.getTimestamp().getTimeInMillis());
                            break;
                        }
                    }
                }
            }

        }
    } catch (IOException e) {
        throw new TransfertException(current_file_transfert, null, e);
    }
    for (FTPFile ff : files) {
        if (!ff.getName().equals(".") && !ff.getName().equals("..")) {
            boolean found = false;
            for (File f : _directory_src.listFiles()) {
                if (f.getName().equals(ff.getName()) && f.isDirectory() == ff.isDirectory()) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                if (ff.isDirectory()) {
                    FileTools.removeDirectory(ftpClient, _directory_dst + ff.getName());
                } else {
                    ftpClient.deleteFile(_directory_dst + ff.getName());
                }
            }
        }
    }
}

From source file:com.microsoft.azuretools.utils.WebAppUtils.java

public static boolean doesRemoteFileExist(FTPClient ftp, String path, String fileName) throws IOException {
    FTPFile[] files = ftp.listFiles(path);
    for (FTPFile file : files) {
        if (file.isFile() && file.getName().equalsIgnoreCase(fileName)) {
            return true;
        }/* w  ww .j  av a  2 s  .  c  o m*/
    }
    return false;
}