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:Main.java

public static void main(String[] args) {
    FTPClient client = new FTPClient();

    client.connect("ftp.domain.com");
    client.login("admin", "secret");

    String[] names = client.listNames();
    for (String name : names) {
        System.out.println("Name = " + name);
    }//ww w.  j a  va  2s.c o m

    FTPFile[] ftpFiles = client.listFiles();
    for (FTPFile ftpFile : ftpFiles) {
        // Check if FTPFile is a regular file
        if (ftpFile.getType() == FTPFile.FILE_TYPE) {
            System.out.println("FTPFile: " + ftpFile.getName() + "; "
                    + FileUtils.byteCountToDisplaySize(ftpFile.getSize()));
        }
    }
    client.logout();
    client.disconnect();
}

From source file:com.logic.test.FTPSLogic.java

public static void main(String[] args) {
    String serverAdress = "62.2.176.167";
    String username = "RLSFTPRead";
    String password = "ftp4rls";
    int port = 990;
    FTPSClient ftpsClient = new FTPSClient("TLS", true);
    String remoteFile = "REM - Persons Extract.csv";
    File localFile = new File("Persons Extract.csv");

    try {// www . j a v a 2 s . co m
        TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

        //ftpsClient.setTrustManager(trustManager[0]);
        //KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        //kmf.init(null, null);
        //KeyManager km = kmf.getKeyManagers()[0];

        //ftpsClient.setKeyManager(km);
        ftpsClient.setBufferSize(1024 * 1024);
        ftpsClient.setConnectTimeout(100000);
        ftpsClient.connect(InetAddress.getByName(serverAdress), port);
        ftpsClient.setSoTimeout(100000);

        if (ftpsClient.login(username, password)) {
            ftpsClient.execPBSZ(0);
            ftpsClient.execPROT("P");
            ftpsClient.changeWorkingDirectory("/");
            ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpsClient.enterLocalPassiveMode();

            //ftpsClient.retrieveFile(remoteFile, new FileOutputStream(localFile));
            for (FTPFile file : ftpsClient.listFiles()) {
                System.out.println("Nom " + file.getName());
            }

        }
    } catch (SocketException e) {
        ;
    } catch (UnknownHostException e) {
        ;
    } catch (IOException e) {
        ;
    } catch (Exception e) {
        ;
    } finally {
        try {
            ftpsClient.logout();
        } catch (Exception e2) {
        }

        try {
            ftpsClient.disconnect();
        } catch (Exception e2) {
        }
    }
}

From source file:dataflow.examples.TransferFiles.java

public static void main(String[] args) throws IOException, URISyntaxException {
    Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
    List<FilePair> filePairs = new ArrayList<FilePair>();

    URI ftpInput = new URI(options.getInput());

    FTPClient ftp = new FTPClient();
    ftp.connect(ftpInput.getHost());//from w  w w.  j a  v a2 s  .  c  o m

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

    if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        logger.error("FTP server refused connection.");
        throw new RuntimeException("FTP server refused connection.");
    }

    ftp.login("anonymous", "someemail@gmail.com");

    String ftpPath = ftpInput.getPath();
    FTPFile[] files = ftp.listFiles(ftpPath);

    URI gcsUri = null;
    if (options.getOutput().endsWith("/")) {
        gcsUri = new URI(options.getOutput());
    } else {
        gcsUri = new URI(options.getOutput() + "/");
    }

    for (FTPFile f : files) {
        logger.info("File: " + f.getName());
        FilePair p = new FilePair();
        p.server = ftpInput.getHost();
        p.ftpPath = f.getName();

        // URI ftpURI = new URI("ftp", p.server, f.getName(), "");
        p.gcsPath = gcsUri.resolve(FilenameUtils.getName(f.getName())).toString();

        filePairs.add(p);
    }

    ftp.logout();

    Pipeline p = Pipeline.create(options);
    PCollection<FilePair> inputs = p.apply(Create.of(filePairs));
    inputs.apply(ParDo.of(new FTPToGCS()).named("CopyToGCS"))
            .apply(AvroIO.Write.withSchema(FilePair.class).to(options.getOutput()));
    p.run();
}

From source file:cn.zhuqi.mavenssh.web.util.test.FtpTest.java

/**
 * Description: FTP?//from   ww  w . j  av a 2s.c  om
 *
 * @Version1.0
 * @param url FTP?hostname
 * @param port FTP??
 * @param username FTP?
 * @param password FTP?
 * @param remotePath FTP?
 * @param fileName ???
 * @param localPath ??
 * @return
 */
public static boolean downloadFile(String url, int port, String username, String password, String remotePath,
        String fileName, String localPath) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        // FTP?
        if (port > -1) {
            ftp.connect(url, port);
        } else {
            ftp.connect(url);
        }
        ftp.login(username, password);//
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        ftp.changeWorkingDirectory(remotePath);//FTP?
        FTPFile[] fs = ftp.listFiles();
        for (FTPFile ff : fs) {
            if (ff.getName().equals(fileName)) {
                File localFile = new File(localPath + "/" + ff.getName());
                OutputStream is = new FileOutputStream(localFile);
                ftp.retrieveFile(ff.getName(), is);
                is.close();
            }
        }

        ftp.logout();
        success = true;
    } catch (IOException e) {
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
            }
        }
    }
    return success;
}

From source file:com.zurich.lifeac.intra.control.FTPUtil.java

public static void downloadDirectory(FTPClient ftpClient, String parentDir, String currentDir, String saveDir)
        throws IOException {//parentDir=remote_edir ,saveDir=loc_dir
    String dirToList = parentDir;

    if (!currentDir.equals("")) {
        dirToList += "/" + currentDir;
    }// www  .  j a  va 2  s.  c o  m
    System.out.println("downloadDirectory >dirToList:" + dirToList);
    FTPFile[] subFiles = ftpClient.listFiles(dirToList);

    if (subFiles != null && subFiles.length > 0) {
        for (FTPFile aFile : subFiles) {
            String currentFileName = aFile.getName();
            if (currentFileName.equals(".") || currentFileName.equals("..")) {
                // skip parent directory and the directory itself
                continue;
            }
            String filePath = parentDir + "/" + currentDir + "/" + currentFileName;

            if (currentDir.equals("")) {
                filePath = parentDir + "/" + currentFileName;
            }
            //System.out.println(filePath);
            String newDirPath = saveDir + File.separator + currentDir + File.separator + currentFileName;
            if (currentDir.equals("")) {
                newDirPath = saveDir + File.separator + currentFileName;
            }

            if (aFile.isDirectory()) {
                // create the directory in saveDir
                //                    File newDir = new File(newDirPath);
                //                    boolean created = newDir.mkdirs();
                //                    if (created) {
                //                        System.out.println("CREATED the directory: " + newDirPath);
                //                    } else {
                //                        System.out.println("COULD NOT create the directory: " + newDirPath);
                //                    }
                //
                //                    // download the sub directory
                //                    downloadDirectory(ftpClient, dirToList, currentFileName,
                //                            saveDir);
            } else {
                // download the file
                System.out.println("DOWNLOADED the file: " + filePath);
                boolean success = downloadSingleFile(ftpClient, filePath, newDirPath);
                if (success) {

                    //if download success then delete the file.
                    boolean deleted = ftpClient.deleteFile(filePath);
                    if (deleted) {
                        System.out.println("delete the file: " + filePath);
                    } else {
                        System.out.println("COULD NOT delete the file: " + filePath);
                    }

                }
            }
        }
    } else {
        System.out.println("There are no .txt file");
    }
}

From source file:de.l3s.dlg.ncbikraken.ftp.NcbiFTPClient.java

public static void getMedline(MedlineFileType type) {
    FileOutputStream out = null;//from   www.  j  a  va 2 s  .  c o m
    FTPClient ftp = new FTPClient();
    try {
        // Connection String
        LOGGER.info("Connecting to FTP server " + SERVER_NAME);
        ftp.connect(SERVER_NAME);
        ftp.login("anonymous", "");
        ftp.cwd(BASELINE_PATH);
        ftp.cwd(type.getServerPath());

        try {
            ftp.pasv();
        } catch (IOException e) {
            LOGGER.error(
                    "Can not access the passive mode. Maybe a problem with your (Windows) firewall. Just try to run as administrator: \nnetsh advfirewall set global StatefulFTP disable");
            return;
        }

        for (FTPFile file : ftp.listFiles()) {
            if (file.isFile()) {
                File meshF = new File(file.getName());
                LOGGER.debug("Downloading file: " + SERVER_NAME + ":" + BASELINE_PATH + "/"
                        + type.getServerPath() + "/" + meshF.getName());
                out = new FileOutputStream(Configuration.INSTANCE.getMedlineDir() + File.separator + meshF);
                ftp.retrieveFile(meshF.getName(), out);
                out.flush();
                out.close();
            }
        }

    } catch (IOException ioe) {
        LOGGER.error(ioe.getMessage());

    } finally {
        IOUtils.closeQuietly(out);
        try {
            ftp.disconnect();
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
    }

}

From source file:com.microsoft.intellij.util.WAHelper.java

public static boolean isFilePresentOnFTPServer(FTPClient ftp, String fileName) throws IOException {
    boolean filePresent = false;
    FTPFile[] files = ftp.listFiles("/site/wwwroot");
    for (FTPFile file : files) {
        if (file.getName().equalsIgnoreCase(fileName)) {
            filePresent = true;//from   ww  w  .j av a 2 s. c  om
            break;
        }
    }
    return filePresent;
}

From source file:eu.ggnet.dwoss.misc.op.listings.FtpTransfer.java

private static void deleteFilesByType(FTPClient ftp, Collection<String> fileTypesToDelete) throws IOException {
    if (fileTypesToDelete == null || fileTypesToDelete.isEmpty())
        return;/*  w  w  w. j a  v  a  2s .  co m*/
    FTPFile[] existingFiles = ftp.listFiles();
    if (existingFiles == null || existingFiles.length == 0)
        return;
    for (String type : fileTypesToDelete) {
        for (FTPFile ftpFile : existingFiles) {
            if (ftpFile == null)
                continue;
            if (ftpFile.getName().toLowerCase().endsWith(type)) {
                if (!ftp.deleteFile(ftpFile.getName())) {
                    throw new IOException("Could not delete " + ftpFile.getName());
                }
            }
        }
    }
}

From source file:com.jaspersoft.jasperserver.api.engine.common.util.impl.FTPUtil.java

private static boolean exists(FTPClient ftpClient, String fileName) throws Exception {
    if (ftpClient == null)
        throw new JSException("Please connect to FTP server first before changing directory!");
    try {/*  w w w .j  a  v  a  2 s.  c o m*/
        if (log.isDebugEnabled())
            log.debug("FTP Working directory = " + ftpClient.printWorkingDirectory());
        FTPFile[] files = ftpClient.listFiles(ftpClient.printWorkingDirectory());

        if (log.isDebugEnabled())
            log.debug("FTP:  number of files - " + (files == null ? "NULL" : files.length));

        if (files == null)
            return false;
        for (FTPFile ftpFile : files) {
            if (ftpFile.getName().equalsIgnoreCase(fileName))
                return true;
        }
        return false;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
}

From source file:com.peter.javaautoupdater.JavaAutoUpdater.java

public static void run(String ftpHost, int ftpPort, String ftpUsername, String ftpPassword,
        boolean isLocalPassiveMode, boolean isRemotePassiveMode, String basePath, String softwareName,
        String args[]) {/*  ww w .j  a  v a2  s.  c o m*/
    System.out.println("jarName=" + jarName);
    for (String arg : args) {
        if (arg.toLowerCase().trim().equals("-noautoupdate")) {
            return;
        }
    }
    JavaAutoUpdater.basePath = basePath;
    JavaAutoUpdater.softwareName = softwareName;
    JavaAutoUpdater.args = args;

    if (!jarName.endsWith(".jar") || jarName.startsWith("JavaAutoUpdater-")) {
        if (isDebug) {
            jarName = "test.jar";
        } else {
            return;
        }
    }
    JProgressBarDialog d = new JProgressBarDialog(new JFrame(), "Auto updater", true);

    d.progressBar.setIndeterminate(true);
    d.progressBar.setStringPainted(true);
    d.progressBar.setString("Updating");
    //      d.addCancelEventListener(this);
    Thread longRunningThread = new Thread() {
        public void run() {
            d.progressBar.setString("checking latest version");
            System.out.println("checking latest version");

            FTPClient ftp = new FTPClient();
            try {
                ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
                ftp.connect(ftpHost, ftpPort);
                int reply = ftp.getReplyCode();
                System.out.println("reply=" + reply + ", " + FTPReply.isPositiveCompletion(reply));
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    JOptionPane.showMessageDialog(null, "FTP server refused connection", "error",
                            JOptionPane.ERROR_MESSAGE);
                }
                d.progressBar.setString("connected to ftp");
                System.out.println("connected to ftp");
                boolean success = ftp.login(ftpUsername, ftpPassword);
                if (!success) {
                    ftp.disconnect();
                    JOptionPane.showMessageDialog(null, "FTP login fail, can't update software", "error",
                            JOptionPane.ERROR_MESSAGE);
                }
                if (isLocalPassiveMode) {
                    ftp.enterLocalPassiveMode();
                }
                if (isRemotePassiveMode) {
                    ftp.enterRemotePassiveMode();
                }
                FTPFile[] ftpFiles = ftp.listFiles(basePath, new FTPFileFilter() {
                    @Override
                    public boolean accept(FTPFile file) {
                        if (file.getName().startsWith(softwareName)) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                });
                if (ftpFiles.length > 0) {
                    FTPFile targetFile = ftpFiles[ftpFiles.length - 1];
                    System.out.println("targetFile : " + targetFile.getName() + " , " + targetFile.getSize()
                            + "!=" + new File(jarName).length());
                    if (!targetFile.getName().equals(jarName)
                            || targetFile.getSize() != new File(jarName).length()) {
                        int r = JOptionPane.showConfirmDialog(null,
                                "Confirm to update to " + targetFile.getName(), "Question",
                                JOptionPane.YES_NO_OPTION);
                        if (r == JOptionPane.YES_OPTION) {
                            //ftp.enterRemotePassiveMode();
                            d.progressBar.setString("downloading " + targetFile.getName());
                            ftp.setFileType(FTP.BINARY_FILE_TYPE);
                            ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);

                            d.progressBar.setIndeterminate(false);
                            d.progressBar.setMaximum(100);
                            CopyStreamAdapter streamListener = new CopyStreamAdapter() {

                                @Override
                                public void bytesTransferred(long totalBytesTransferred, int bytesTransferred,
                                        long streamSize) {
                                    int percent = (int) (totalBytesTransferred * 100 / targetFile.getSize());
                                    d.progressBar.setValue(percent);
                                }
                            };
                            ftp.setCopyStreamListener(streamListener);
                            try (FileOutputStream fos = new FileOutputStream(targetFile.getName())) {
                                ftp.retrieveFile(basePath + "/" + targetFile.getName(), fos);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            d.progressBar.setString("restarting " + targetFile.getName());
                            restartApplication(targetFile.getName());
                        }
                    }

                }
                ftp.logout();
                ftp.disconnect();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };
    d.thread = longRunningThread;
    d.setVisible(true);
}