Example usage for org.apache.commons.net.ftp FTPClient changeWorkingDirectory

List of usage examples for org.apache.commons.net.ftp FTPClient changeWorkingDirectory

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPClient changeWorkingDirectory.

Prototype

public boolean changeWorkingDirectory(String pathname) throws IOException 

Source Link

Document

Change the current working directory of the FTP session.

Usage

From source file:com.claim.support.FtpUtil.java

public void uploadMutiFileWithFTP(String targetDirectory, FileTransferController fileTransferController) {
    try {//from  www.j av  a  2 s  .c  om
        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.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. j  a  v a 2 s. c  om
        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:GridFDock.DataDistribute.java

public Status CreateDirectory(String remote, FTPClient ftpClient) throws IOException {
    Status status = Status.Create_Directory_Success;
    String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
    if (!directory.equalsIgnoreCase("/")
            && !ftpClient.changeWorkingDirectory(new String(directory.getBytes(CODING_1), CODING_2))) {
        int start = 0;
        int end = 0;
        if (directory.startsWith("/")) {
            start = 1;/*from w  ww  .  j ava  2  s .c om*/
        } else {
            start = 0;
        }
        end = directory.indexOf("/", start);
        while (true) {
            String subDirectory = new String(remote.substring(start, end).getBytes(CODING_1), CODING_2);
            if (!ftpClient.changeWorkingDirectory(subDirectory)) {
                if (ftpClient.makeDirectory(subDirectory)) {
                    ftpClient.changeWorkingDirectory(subDirectory);
                } else {
                    System.out.println("the failure for creating directory.");
                    return Status.Create_Directory_Fail;
                }
            }

            start = end + 1;
            end = directory.indexOf("/", start);// "/" is a token for making
            // fold.

            if (end <= start) {
                break;
            }
        }
    }
    return status;
}

From source file:com.maxl.java.amikodesk.Emailer.java

private void uploadToFTPServer(Author author, String name, String path) {
    FTPClient ftp_client = new FTPClient();
    try {// w ww . ja va 2  s  . c o  m
        ftp_client.connect(author.getS(), 21);
        ftp_client.login(author.getL(), author.getP());
        ftp_client.enterLocalPassiveMode();
        ftp_client.changeWorkingDirectory(author.getO());
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }

        File local_file = new File(path);
        String remote_file = name + ".csv";
        InputStream is = new FileInputStream(local_file);
        System.out.print("Uploading file " + name + " to server " + author.getS() + "... ");

        boolean done = ftp_client.storeFile(remote_file, is);
        if (done)
            System.out.println("file uploaded successfully.");
        else
            System.out.println("error.");
        is.close();
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.geotrackin.gpslogger.senders.ftp.Ftp.java

public synchronized static boolean Upload(String server, String username, String password, String directory,
        int port, boolean useFtps, String protocol, boolean implicit, InputStream inputStream,
        String fileName) {/*from   w  ww . ja v a 2  s. co m*/
    FTPClient client = null;

    try {
        if (useFtps) {
            client = new FTPSClient(protocol, implicit);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(null, null);
            KeyManager km = kmf.getKeyManagers()[0];
            ((FTPSClient) client).setKeyManager(km);
        } else {
            client = new FTPClient();
        }

    } catch (Exception e) {
        tracer.error("Could not create FTP Client", e);
        return false;
    }

    try {
        tracer.debug("Connecting to FTP");
        client.connect(server, port);
        showServerReply(client);

        tracer.debug("Logging in to FTP server");
        if (client.login(username, password)) {
            client.enterLocalPassiveMode();
            showServerReply(client);

            tracer.debug("Uploading file to FTP server " + server);

            tracer.debug("Checking for FTP directory " + directory);
            FTPFile[] existingDirectory = client.listFiles(directory);
            showServerReply(client);

            if (existingDirectory.length <= 0) {
                tracer.debug("Attempting to create FTP directory " + directory);
                //client.makeDirectory(directory);
                ftpCreateDirectoryTree(client, directory);
                showServerReply(client);

            }

            client.changeWorkingDirectory(directory);
            boolean result = client.storeFile(fileName, inputStream);
            inputStream.close();
            showServerReply(client);
            if (result) {
                tracer.debug("Successfully FTPd file " + fileName);
            } else {
                tracer.debug("Failed to FTP file " + fileName);
                return false;
            }

        } else {
            tracer.debug("Could not log in to FTP server");
            return false;
        }

    } catch (Exception e) {
        tracer.error("Could not connect or upload to FTP server.", e);
        return false;
    } finally {
        try {
            tracer.debug("Logging out of FTP server");
            client.logout();
            showServerReply(client);

            tracer.debug("Disconnecting from FTP server");
            client.disconnect();
            showServerReply(client);
        } catch (Exception e) {
            tracer.error("Could not logout or disconnect", e);
            return false;
        }
    }

    return true;
}

From source file:adams.flow.source.FTPLister.java

/**
 * Executes the flow item.//from w  ww . ja v a2s.c o  m
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
protected String doExecute() {
    String result;
    FTPClient client;
    FTPFile[] files;

    result = null;

    m_Queue.clear();
    client = m_Connection.getFTPClient();
    if (m_ListDirs) {
        try {
            if (m_RemoteDir.length() > 0)
                client.changeWorkingDirectory(m_RemoteDir);
            files = client.listDirectories();
            for (FTPFile file : files) {
                if (isStopped())
                    break;
                if (file == null)
                    continue;
                if (m_RegExp.isEmpty() || m_RegExp.isMatchAll() || m_RegExp.isMatch(file.getName()))
                    m_Queue.add(file.getName());
            }
        } catch (Exception e) {
            result = handleException("Failed to list directories in '" + m_RemoteDir + "': ", e);
        }
    }

    if (result == null) {
        if (m_ListFiles) {
            try {
                if (m_RemoteDir.length() > 0)
                    client.changeWorkingDirectory(m_RemoteDir);
                files = client.listFiles();
                for (FTPFile file : files) {
                    if (isStopped())
                        break;
                    if (file == null)
                        continue;
                    if (file.isDirectory())
                        continue;
                    if (m_RegExp.isEmpty() || m_RegExp.isMatchAll() || m_RegExp.isMatch(file.getName()))
                        m_Queue.add(file.getName());
                }
            } catch (Exception e) {
                result = handleException("Failed to list files in '" + m_RemoteDir + "': ", e);
            }
        }
    }

    if (isStopped())
        m_Queue.clear();

    return result;
}

From source file:FTP.Uploader.java

public void uploadFile(String filename) throws IOException {
    FTPClient ftpclient = new FTPClient();
    FileInputStream fis = null;/*from   ww  w  .j ava2s.  co  m*/
    boolean result;
    String ftpServerAddress = "shamalmahesh.net78.net";
    String userName = "a9959679";
    String password = "9P3IckDo";

    try {
        ftpclient.connect(ftpServerAddress);
        result = ftpclient.login(userName, password);

        if (result == true) {
            System.out.println("Logged in Successfully !");
        } else {
            System.out.println("Login Fail!");
            return;
        }
        ftpclient.enterLocalPassiveMode();
        ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

        ftpclient.changeWorkingDirectory("/public_html/testing");

        //            File file = new File("D:/jpg/wq.jpg");
        File file = new File(filename);
        String testName = file.getName();
        fis = new FileInputStream(file);
        System.out.println(ftpclient.getBufferSize());
        // Upload file to the ftp server
        result = ftpclient.storeFile(testName, fis);
        if (result == true) {
            System.out.println("File is uploaded successfully");
        } else {
            System.out.println("File uploading failed");
        }
        ftpclient.logout();
    } catch (FTPConnectionClosedException e) {
        e.printStackTrace();
    } finally {
        try {
            ftpclient.disconnect();
        } catch (FTPConnectionClosedException e) {
            System.out.println(e);
        }
    }
}

From source file:com.eryansky.common.utils.ftp.FtpFactory.java

/**
 * FTP?./*from  www .j  a v  a 2 s  .co  m*/
 * 
 * @param remotePath
 *            FTP?
 * @param fileName
 *            ???
 * @param localPath
 *            ??
 * @return
 */
public boolean ftpDownFile(String remotePath, String fileName, String localPath) {
    // ?
    boolean success = false;
    // FTPClient
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding("GBK");
    try {
        int reply;
        // FTP?
        // ??ftp.connect(url)?FTP?
        ftp.connect(url, port);
        // ftp
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        // 
        ftp.changeWorkingDirectory(remotePath);
        // 
        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();
                success = true;
            }
        }
        ftp.logout();
        // ?

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}

From source file:dk.dma.dmiweather.service.FTPLoader.java

/**
 * Check for files every 10 minutes. New files are given to the gridWeatherService
 *///from w w w  . j  a va 2 s  .c  o m
@Scheduled(initialDelay = 1000, fixedDelay = 10 * 60 * 1000)
public void checkFiles() {
    log.info("Checking FTP files at DMI.");
    FTPClient client = new FTPClient();
    try {
        client.setDataTimeout(20 * 1000);
        client.setBufferSize(1024 * 1024);
        client.connect(hostname);
        if (client.login("anonymous", "")) {
            try {
                client.enterLocalPassiveMode();
                client.setFileType(FTP.BINARY_FILE_TYPE);
                for (ForecastConfiguration configuration : configurations) {
                    // DMI creates a Newest link once all files have been created
                    if (client.changeWorkingDirectory(configuration.getFolder() + "/Newest")) {
                        if (client.getReplyCode() != 250) {
                            log.error("Did not get reply 250 as expected, got {} ", client.getReplyCode());
                        }
                        String workingDirectory = new File(client.printWorkingDirectory()).getName();
                        String previousNewest = newestDirectories.get(configuration);
                        if (!workingDirectory.equals(previousNewest)) {
                            // a new directory for this configuration is available on the server
                            FTPFile[] listFiles = client.listFiles();
                            List<FTPFile> files = Arrays.stream(listFiles)
                                    .filter(f -> configuration.getFilePattern().matcher(f.getName()).matches())
                                    .collect(Collectors.toList());

                            try {
                                Map<File, Instant> localFiles = transferFilesIfNeeded(client, workingDirectory,
                                        files);
                                gridWeatherService.newFiles(localFiles, configuration);
                            } catch (IOException e) {
                                log.warn("Unable to get new weather files from DMI", e);
                            }

                            if (previousNewest != null) {
                                File previous = new File(tempDirLocation, previousNewest);
                                deleteRecursively(previous);
                            }
                            newestDirectories.put(configuration, workingDirectory);
                        }

                    } else {
                        gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
                        log.error("Unable to change ftp directory to {}", configuration.getFolder());
                    }
                }
            } finally {
                try {
                    client.logout();
                } catch (IOException e) {
                    log.info("Failed to logout", e);
                }
            }
        } else {
            gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
            log.error("Unable to login to {}", hostname);
        }

    } catch (IOException e) {
        gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
        log.error("Unable to update weather files from DMI", e);
    } finally {
        try {
            client.disconnect();
        } catch (IOException e) {
            log.info("Failed to disconnect", e);
        }
    }
    log.info("Check completed.");
}

From source file:adams.core.io.lister.FtpDirectoryLister.java

/**
 * Performs the recursive search. Search goes deeper if != 0 (use -1 to
 * start with for infinite search)./*from   w w  w .j  a  v  a 2 s  .c  om*/
 *
 * @param client   the client to use
 * @param current   the current directory
 * @param files   the files collected so far
 * @param depth   the depth indicator (searched no deeper, if 0)
 * @throws Exception   if listing fails
 */
protected void search(FTPClient client, String current, List<SortContainer> files, int depth) throws Exception {
    List<FTPFile> currFiles;
    int i;
    FTPFile entry;
    SortContainer cont;

    if (depth == 0)
        return;

    if (getDebug())
        getLogger().info("search: current=" + current + ", depth=" + depth);

    client.changeWorkingDirectory(current);
    currFiles = new ArrayList<>();
    currFiles.addAll(Arrays.asList(client.listFiles()));
    if (currFiles.size() == 0) {
        if (getDebug())
            getLogger().info("No files listed!");
        return;
    }

    for (i = 0; i < currFiles.size(); i++) {
        // do we have to stop?
        if (m_Stopped)
            break;

        entry = currFiles.get(i);

        // directory?
        if (entry.isDirectory()) {
            // ignore "." and ".."
            if (entry.getName().equals(".") || entry.getName().equals(".."))
                continue;

            // search recursively?
            if (m_Recursive)
                search(client, current + "/" + entry.getName(), files, depth - 1);

            if (m_ListDirs) {
                // does name match?
                if (!m_RegExp.isEmpty() && !m_RegExp.isMatch(entry.getName()))
                    continue;

                files.add(new SortContainer(new FtpFileObject(current, entry, m_Client), m_Sorting));
            }
        } else {
            if (m_ListFiles) {
                // does name match?
                if (!m_RegExp.isEmpty() && !m_RegExp.isMatch(entry.getName()))
                    continue;

                files.add(new SortContainer(new FtpFileObject(current, entry, m_Client), m_Sorting));
            }
        }
    }
}