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:org.ow2.proactive.scheduler.examples.FTPConnector.java

private List<String> ftpPut(FTPClient ftpClient) throws IOException {
    List<String> filesRelativePathName = new ArrayList<>();
    getOut().println("Exporting file(s) from " + ftpLocalRelativePath + " to " + ftpRemoteRelativePath);
    File localFile = new File(ftpLocalRelativePath);
    if (!localFile.exists()) {
        throw new IllegalArgumentException(localFile + " not found. Please, enter a valid path.");
    }//from w w w .j a  v a 2 s.co m
    // if the ftp remote file path does not exist then it is created.
    makeRemoteDirectoriesIfNotExist(ftpClient, Paths.get(ftpRemoteRelativePath));

    // If it is a single file:
    if (localFile.isFile()) {
        getOut().println("A single FILE to upload");
        ftpClient.changeWorkingDirectory(ftpRemoteRelativePath);
        filesRelativePathName.add(uploadSingleFile(ftpClient, ftpLocalRelativePath, localFile.getName()));

    }
    // If it is a folder, upload all its contents recursively
    else {
        getOut().println("A DIRECTORY to upload");
        ftpClient.changeWorkingDirectory(ftpRemoteRelativePath);
        filesRelativePathName.addAll(new HashSet(uploadDirectory(ftpClient, "", ftpLocalRelativePath, "")));
    }
    getOut().println("END Export file(s) to FTP.");
    return filesRelativePathName;
}

From source file:org.ow2.proactive.scheduler.examples.FTPConnector.java

private List<String> uploadDirectory(FTPClient ftpClient, String remoteDirPath, String localParentDir,
        String remoteParentDir) throws IOException {
    List<String> filesRelativePathName = new ArrayList<>();

    File localDir = new File(localParentDir);
    getOut().println("LISTING directory: " + localDir.getName());

    File[] subFiles = localDir.listFiles();
    for (File item : subFiles) {
        if (item.isFile()) {
            // upload the file
            String localFilePath = item.getAbsolutePath();
            getOut().println("About to UPLOAD the file: " + item.getName());
            filesRelativePathName.add(uploadSingleFile(ftpClient, localFilePath, item.getName()));

        } else {/*from w w  w . jav  a 2  s  .  c om*/
            // create directory on the server
            createRemoteDirectoryIfNotExists(ftpClient, item.getName());

            // upload the sub directory
            String parent = Paths.get(remoteParentDir, item.getName()).toString();
            if (remoteParentDir.equals("")) {
                parent = item.getName();
            }

            localParentDir = item.getAbsolutePath();
            filesRelativePathName.addAll(uploadDirectory(ftpClient, remoteDirPath, localParentDir, parent));
            //cd ..
            ftpClient.changeWorkingDirectory(PARENT_FOLDER);
        }
    }
    return filesRelativePathName;
}

From source file:org.ow2.proactive.scheduler.examples.FTPConnector.java

private void createRemoteDirectoryIfNotExists(FTPClient ftpClient, String dirPath) throws IOException {
    ftpClient.changeWorkingDirectory(dirPath);
    int returnCode = ftpClient.getReplyCode();
    if (returnCode == 550) {
        createRemoteDirectory(ftpClient, dirPath);
        ftpClient.changeWorkingDirectory(dirPath);

    }//w w  w . j  a  v a2  s  . co m

}

From source file:org.ramadda.repository.monitor.FtpAction.java

/**
 * _more_//  w w w. j a v  a 2  s .co m
 *
 *
 * @param monitor _more_
 * @param entry _more_
 */
protected void entryMatched(EntryMonitor monitor, Entry entry) {
    FTPClient ftpClient = new FTPClient();
    try {
        Resource resource = entry.getResource();
        if (!resource.isFile()) {
            return;
        }
        if (server.length() == 0) {
            return;
        }

        String passwordToUse = monitor.getRepository().getPageHandler().processTemplate(password, false);
        ftpClient.connect(server);
        if (user.length() > 0) {
            ftpClient.login(user, password);
        }
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            monitor.handleError("FTP server refused connection:" + server, null);

            return;
        }
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        if (directory.length() > 0) {
            ftpClient.changeWorkingDirectory(directory);
        }

        String filename = monitor.getRepository().getEntryManager().replaceMacros(entry, fileTemplate);

        InputStream is = new BufferedInputStream(
                monitor.getRepository().getStorageManager().getFileInputStream(new File(resource.getPath())));
        boolean ok = ftpClient.storeUniqueFile(filename, is);
        is.close();
        if (ok) {
            monitor.logInfo("Wrote file:" + directory + " " + filename);
        } else {
            monitor.handleError("Failed to write file:" + directory + " " + filename, null);
        }
    } catch (Exception exc) {
        monitor.handleError("Error posting to FTP:" + server, exc);
    } finally {
        try {
            ftpClient.logout();
        } catch (Exception exc) {
        }
        try {
            ftpClient.disconnect();
        } catch (Exception exc) {
        }
    }
}

From source file:org.ramadda.repository.type.FtpTypeHandler.java

/**
 * _more_//from  w ww  .j  a  v a2  s  .com
 *
 * @param ftpClient _more_
 * @param path _more_
 *
 * @return _more_
 *
 * @throws Exception _more_
 */
private static boolean isDir(FTPClient ftpClient, String path) throws Exception {
    boolean isDir = false;
    //A hack but assume anything with a "." is not a directory
    //The problem is how to determine if the path is a directory
    //If we do changeWorkingDir for every file this becomes very 
    //expensive

    if (path.indexOf(".") < 0) {
        isDir = ftpClient.changeWorkingDirectory(path);
    }

    return isDir;
}

From source file:org.ramadda.repository.type.FtpTypeHandler.java

/**
 * _more_// ww  w  . j  a  v a 2s .c  o  m
 *
 * @param request _more_
 * @param mainEntry _more_
 * @param parentEntry _more_
 * @param synthId _more_
 *
 * @return _more_
 *
 * @throws Exception _more_
 */
public List<String> getSynthIds(Request request, Entry mainEntry, Entry parentEntry, String synthId)
        throws Exception {
    long t0 = System.currentTimeMillis();
    List<String> ids = new ArrayList<String>();

    Object[] values = mainEntry.getValues();
    String baseDir = (String) values[COL_BASEDIR];
    String path = getPathFromId(synthId, baseDir);

    /*        boolean descending = !request.get(ARG_ASCENDING, false);
    if (request.getString(ARG_ORDERBY, "").equals("name")) {
    files = IOUtil.sortFilesOnName(files, descending);
    } else {
    files = IOUtil.sortFilesOnAge(files, descending);
    }*/
    long t1 = System.currentTimeMillis();

    FTPClient ftpClient = getFtpClient(mainEntry);
    if (ftpClient == null) {
        return ids;
    }
    long t2 = System.currentTimeMillis();
    //        System.err.println ("getFtpClient:" + (t2-t1));

    try {
        String pattern = (String) values[COL_FILE_PATTERN];
        if ((pattern != null) && (pattern.trim().length() == 0)) {
            pattern = null;
        }
        boolean isDir = ftpClient.changeWorkingDirectory(path);
        if (isDir) {
            boolean checkReadme = parentEntry.getDescription().length() == 0;
            checkReadme = false;
            long t3 = System.currentTimeMillis();
            FTPFile[] files = ftpClient.listFiles(path);
            long t4 = System.currentTimeMillis();
            //                System.err.println ("listFiles:" + (t4-t3));

            for (int i = 0; i < files.length; i++) {
                String name = files[i].getName().toLowerCase();
                if ((pattern != null) && !name.matches(pattern)) {
                    continue;
                }
                if (checkReadme) {
                    if (name.equals("readme") || name.equals("readme.txt")) {
                        try {
                            InputStream fis = ftpClient.retrieveFileStream(path + "/" + files[i].getName());
                            if (fis != null) {
                                String desc = HtmlUtils.entityEncode(IOUtil.readInputStream(fis));
                                parentEntry.setDescription(HtmlUtils.pre(desc));
                                fis.close();
                                ftpClient.completePendingCommand();
                            }
                        } catch (Exception exc) {
                            //                            exc.printStackTrace();
                        }
                    }
                }

                putCache(mainEntry, path + "/" + files[i].getName(), files[i]);
                ids.add(getSynthId(mainEntry, baseDir, path, files[i]));
            }
        }
    } finally {
        closeConnection(ftpClient);
    }
    long t5 = System.currentTimeMillis();

    //        System.err.println ("getSynthIds:" + (t5-t0));
    return ids;
}

From source file:org.shept.util.FtpFileCopy.java

/**
 * Creates the needed directories if necessary.
 * @param ftpClient A <code>FTPClient</code> being <b>connected</b>.
 * @param basePath The base path. This one <b>has to exist</b> on the ftp server!
 * @param path The path to be created.//  www .j  a v  a 2 s. co m
 * @throws IOException IN case of an error.
 */
private boolean ensureFtpDirectory(FTPClient ftpClient, String basePath, String path) throws IOException {
    ftpClient.changeWorkingDirectory(basePath);
    StringTokenizer tokenizer = new StringTokenizer(path, "/");
    while (tokenizer.hasMoreTokens()) {
        String folder = tokenizer.nextToken();
        FTPFile[] ftpFile = ftpClient.listFiles(folder);
        if (ftpFile.length == 0) {
            // create the directoy
            if (!ftpClient.makeDirectory(folder)) {
                logger.error(
                        "Ftp Creating the destination directory did not succeed " + ftpClient.getReplyString());
                return false;
            }
        }
        ftpClient.changeWorkingDirectory(folder);
    }
    return true;
}

From source file:org.spka.cursus.publish.website.ftp.PrepareDirectory.java

public void on(FTPClient ftp) throws IOException {
    if (!ftp.changeWorkingDirectory(Constants.RESULTS_DIR)) {
        if (!ftp.makeDirectory(Constants.RESULTS_DIR)) {
            throw new IllegalStateException("Unable to create results dir");
        }// w  w  w  .  j  a  v a 2  s.c om

        if (!ftp.changeWorkingDirectory(Constants.RESULTS_DIR)) {
            throw new IllegalStateException("Unable to change to results dir");
        }
    }

    ftp.changeWorkingDirectory("/");
}

From source file:org.structr.files.ftp.FtpDirectoriesTest.java

public void test03MkdirCd() {

    FTPClient ftp = setupFTPClient();
    final String name1 = "/FTPdir1";

    try (final Tx tx = app.tx()) {

        FTPFile[] dirs = ftp.listDirectories();

        assertNotNull(dirs);//from w  w w .  j av a 2  s  .c  o  m
        assertEquals(0, dirs.length);

        // Create folder by mkdir FTP command
        ftp.makeDirectory(name1);

        tx.success();

    } catch (IOException | FrameworkException ex) {
        ex.printStackTrace();
        fail("Unexpected exception: " + ex.getMessage());
    }

    try (final Tx tx = app.tx()) {

        ftp.changeWorkingDirectory(name1);

        assertEmptyDirectory(ftp);

        String newWorkingDirectory = ftp.printWorkingDirectory();
        assertEquals(name1, newWorkingDirectory);

        ftp.disconnect();

        tx.success();

    } catch (IOException | FrameworkException ex) {
        ex.printStackTrace();
        fail("Unexpected exception: " + ex.getMessage());
    }
}

From source file:org.structr.files.ftp.FtpDirectoriesTest.java

public void test04MkdirCdMkdirCd() {

    FTPClient ftp = setupFTPClient();

    try (final Tx tx = StructrApp.getInstance(securityContext).tx()) {

        assertEmptyDirectory(ftp);/*from  w  w w .ja  v  a 2 s .co  m*/

        String name1 = "/FTPdir1";

        // Create folder by mkdir FTP command
        ftp.makeDirectory(name1);

        ftp.changeWorkingDirectory(name1);

        String newWorkingDirectory = ftp.printWorkingDirectory();
        assertEquals(name1, newWorkingDirectory);

        assertEmptyDirectory(ftp);

        String name2 = name1.concat("/").concat("FTPdir2");

        // Create folder by mkdir FTP command
        ftp.makeDirectory(name2);

        ftp.changeWorkingDirectory(name2);

        newWorkingDirectory = ftp.printWorkingDirectory();
        assertEquals(name2, newWorkingDirectory);

        assertEmptyDirectory(ftp);

        ftp.disconnect();

        tx.success();

    } catch (IOException | FrameworkException ex) {
        ex.printStackTrace();
        fail("Unexpected exception: " + ex.getMessage());
    }
}