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.moxie.ftp.FTP.java

/**
 * Create the specified directory on the remote host.
 *
 * @param ftp The FTP client connection/*w  w w  .j  a va2  s . c  om*/
 * @param dir The directory to create (format must be correct for host
 *      type)
 * @throws IOException  in unknown circumstances
 * @throws BuildException if ignoreNoncriticalErrors has not been set to true
 *         and a directory could not be created, for instance because it was
 *         already existing. Precisely, the codes 521, 550 and 553 will trigger
 *         a BuildException
 */
protected void makeRemoteDir(FTPClient ftp, String dir) throws IOException, BuildException {
    String workingDirectory = ftp.printWorkingDirectory();
    if (verbose) {
        if (dir.indexOf("/") == 0 || workingDirectory == null) {
            log("Creating directory: " + dir + " in /");
        } else {
            log("Creating directory: " + dir + " in " + workingDirectory);
        }
    }
    if (dir.indexOf("/") == 0) {
        ftp.changeWorkingDirectory("/");
    }
    String subdir = "";
    StringTokenizer st = new StringTokenizer(dir, "/");
    while (st.hasMoreTokens()) {
        subdir = st.nextToken();
        log("Checking " + subdir, Project.MSG_DEBUG);
        if (!ftp.changeWorkingDirectory(subdir)) {
            if (!ftp.makeDirectory(subdir)) {
                // codes 521, 550 and 553 can be produced by FTP Servers
                //  to indicate that an attempt to create a directory has
                //  failed because the directory already exists.
                int rc = ftp.getReplyCode();
                if (!(ignoreNoncriticalErrors && (rc == CODE_550 || rc == CODE_553 || rc == CODE_521))) {
                    throw new BuildException("could not create directory: " + ftp.getReplyString());
                }
                if (verbose) {
                    log("Directory already exists");
                }
            } else {
                if (verbose) {
                    log("Directory created OK");
                }
                ftp.changeWorkingDirectory(subdir);
            }
        }
    }
    if (workingDirectory != null) {
        ftp.changeWorkingDirectory(workingDirectory);
    }
}

From source file:org.moxie.ftp.FTPTaskMirrorImpl.java

/**
 * Create the specified directory on the remote host.
 *
 * @param ftp The FTP client connection/*from   ww w . j a v  a2s. c  o  m*/
 * @param dir The directory to create (format must be correct for host
 *      type)
 * @throws IOException  in unknown circumstances
 * @throws BuildException if ignoreNoncriticalErrors has not been set to true
 *         and a directory could not be created, for instance because it was
 *         already existing. Precisely, the codes 521, 550 and 553 will trigger
 *         a BuildException
 */
protected void makeRemoteDir(FTPClient ftp, String dir) throws IOException, BuildException {
    String workingDirectory = ftp.printWorkingDirectory();
    if (task.isVerbose()) {
        if (dir.indexOf("/") == 0 || workingDirectory == null) {
            task.log("Creating directory: " + dir + " in /");
        } else {
            task.log("Creating directory: " + dir + " in " + workingDirectory);
        }
    }
    if (dir.indexOf("/") == 0) {
        ftp.changeWorkingDirectory("/");
    }
    String subdir = "";
    StringTokenizer st = new StringTokenizer(dir, "/");
    while (st.hasMoreTokens()) {
        subdir = st.nextToken();
        task.log("Checking " + subdir, Project.MSG_DEBUG);
        if (!ftp.changeWorkingDirectory(subdir)) {
            if (!ftp.makeDirectory(subdir)) {
                // codes 521, 550 and 553 can be produced by FTP Servers
                //  to indicate that an attempt to create a directory has
                //  failed because the directory already exists.
                int rc = ftp.getReplyCode();
                if (!(task.isIgnoreNoncriticalErrors()
                        && (rc == CODE_550 || rc == CODE_553 || rc == CODE_521))) {
                    throw new BuildException("could not create directory: " + ftp.getReplyString());
                }
                if (task.isVerbose()) {
                    task.log("Directory already exists");
                }
            } else {
                if (task.isVerbose()) {
                    task.log("Directory created OK");
                }
                ftp.changeWorkingDirectory(subdir);
            }
        }
    }
    if (workingDirectory != null) {
        ftp.changeWorkingDirectory(workingDirectory);
    }
}

From source file:org.mule.modules.FtpUtils.java

public static boolean fileExists(FTPClient client, String filePath, String fileName) {
    try {/*www  . j a  v  a  2  s  .  c  om*/
        String fullPath = createFullPath(filePath, fileName);
        client.changeWorkingDirectory(filePath);
        if (client.listFiles(fileName).length == 1) {
            return true;
        } else {
            return false;
        }
    } catch (IOException e) {
        throw new FtpLiteException("Error looking up the file");
    }
}

From source file:org.mule.transport.ftp.FtpConnector.java

/**
 * Creates a new FTPClient that logs in and changes the working directory using the data
 * provided in <code>endpoint</code>.
 *//*from   w  w  w .  java 2  s .  c om*/
protected FTPClient createFtpClient(ImmutableEndpoint endpoint) throws Exception {
    EndpointURI uri = endpoint.getEndpointURI();
    FTPClient client = this.getFtp(uri);

    this.enterActiveOrPassiveMode(client, endpoint);
    this.setupFileType(client, endpoint);

    String path = uri.getPath();

    // only change directory if one was configured
    if (StringUtils.isNotBlank(path)) {
        // MULE-2400: if the path begins with '~' we must strip the first '/' to make things
        // work with FTPClient
        if ((path.length() >= 2) && (path.charAt(1) == '~')) {
            path = path.substring(1);
        }

        if (!client.changeWorkingDirectory(path)) {
            throw new IOException(MessageFormat.format(
                    "Failed to change working directory to {0}. Ftp error: {1}", path, client.getReplyCode()));
        }
    }
    return client;
}

From source file:org.openconcerto.ftp.FTPUtils.java

static public final void saveR(FTPClient ftp, File local) throws IOException {
    local.mkdirs();// w w w.j  a  va  2 s.  c  o  m
    for (FTPFile child : ftp.listFiles()) {
        final String childName = child.getName();
        if (childName.indexOf('.') != 0) {
            if (child.isDirectory()) {
                ftp.changeWorkingDirectory(childName);
                saveR(ftp, new File(local, childName));
                ftp.changeToParentDirectory();
            } else {
                final OutputStream outs = new FileOutputStream(new File(local, childName));
                ftp.retrieveFile(childName, outs);
                outs.close();
            }
        }
    }
}

From source file:org.openconcerto.ftp.FTPUtils.java

static public final void rmR(final FTPClient ftp, final String toRm) throws IOException {
    final String cwd = ftp.printWorkingDirectory();
    // si on ne peut cd, le dossier n'existe pas
    if (ftp.changeWorkingDirectory(toRm)) {
        recurse(ftp, new ExnClosure<FTPFile, IOException>() {
            @Override// ww w  .j a v  a2  s .  c  o  m
            public void executeChecked(FTPFile input) throws IOException {
                final boolean res;
                if (input.isDirectory())
                    res = ftp.removeDirectory(input.getName());
                else
                    res = ftp.deleteFile(input.getName());
                if (!res)
                    throw new IOException("unable to delete " + input);
            }
        }, RecursionType.DEPTH_FIRST);
    }
    ftp.changeWorkingDirectory(cwd);
    ftp.removeDirectory(toRm);
}

From source file:org.openconcerto.ftp.FTPUtils.java

static public final void recurse(FTPClient ftp, ExnClosure<FTPFile, ?> c, RecursionType type)
        throws IOException {
    for (FTPFile child : ftp.listFiles()) {
        if (child.getName().indexOf('.') != 0) {
            if (type == RecursionType.BREADTH_FIRST)
                c.executeCheckedWithExn(child, IOException.class);
            if (child.isDirectory()) {
                ftp.changeWorkingDirectory(child.getName());
                recurse(ftp, c, type);//from  w  ww  .ja  va 2  s . c o m
                ftp.changeToParentDirectory();
            }
            if (type == RecursionType.DEPTH_FIRST)
                c.executeCheckedWithExn(child, IOException.class);
        }
    }
}

From source file:org.opennms.systemreport.formatters.FtpSystemReportFormatter.java

@Override
public void end() {
    m_zipFormatter.end();//  ww  w  .ja va  2  s .c  o  m
    IOUtils.closeQuietly(m_outputStream);

    final FTPClient ftp = new FTPClient();
    FileInputStream fis = null;
    try {
        if (m_url.getPort() == -1 || m_url.getPort() == 0 || m_url.getPort() == m_url.getDefaultPort()) {
            ftp.connect(m_url.getHost());
        } else {
            ftp.connect(m_url.getHost(), m_url.getPort());
        }
        if (m_url.getUserInfo() != null && m_url.getUserInfo().length() > 0) {
            final String[] userInfo = m_url.getUserInfo().split(":", 2);
            ftp.login(userInfo[0], userInfo[1]);
        } else {
            ftp.login("anonymous", "opennmsftp@");
        }
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            LOG.error("FTP server refused connection.");
            return;
        }

        String path = m_url.getPath();
        if (path.endsWith("/")) {
            LOG.error("Your FTP URL must specify a filename.");
            return;
        }
        File f = new File(path);
        path = f.getParent();
        if (!ftp.changeWorkingDirectory(path)) {
            LOG.info("unable to change working directory to {}", path);
            return;
        }
        LOG.info("uploading {} to {}", f.getName(), path);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        fis = new FileInputStream(m_zipFile);
        if (!ftp.storeFile(f.getName(), fis)) {
            LOG.info("unable to store file");
            return;
        }
        LOG.info("finished uploading");
    } catch (final Exception e) {
        LOG.error("Unable to FTP file to {}", m_url, e);
    } finally {
        IOUtils.closeQuietly(fis);
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
}

From source file:org.openspice.vfs.ftp.FtpTools.java

public static final boolean folderExists(final FTPClient ftpc, final String path) {
    try {/*  w  w w .ja  v a 2  s. c o  m*/
        return ftpc.changeWorkingDirectory(path);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

private List<String> ftpGet(FTPClient ftpClient) throws IOException {
    List<String> filesRelativePathName;
    getOut().println("Importing file(s) from " + ftpRemoteRelativePath + " to " + ftpLocalRelativePath);
    FTPFile[] ftpFile = ftpClient.listFiles(ftpRemoteRelativePath);
    if (ftpFile.length == 0) {
        throw new IllegalArgumentException(ftpRemoteRelativePath + " not found. Please, enter a valid path.");
    }/*  ww w .j  a  v  a  2s  .co m*/
    filesRelativePathName = new ArrayList<>();

    // If it is a single file:
    if (ftpFile.length == 1 && ftpRemoteRelativePath.contains(ftpFile[0].getName())) {
        String saveFilePath = Paths
                .get(ftpLocalRelativePath, Paths.get(ftpFile[0].getName()).getFileName().toString()).toString();
        filesRelativePathName.add(downloadSingleFile(ftpClient, ftpRemoteRelativePath, saveFilePath));

        // If the file is a zip, and ftpExtractArchive is set to true
        if (ftpExtractArchive && ftpRemoteRelativePath.endsWith(".zip")) {
            ZipUtil.unpack(new File(saveFilePath), new File(ftpLocalRelativePath));
        }
    }
    // If it is a folder, download all its contents recursively
    else {
        ftpClient.changeWorkingDirectory(ftpRemoteRelativePath);
        filesRelativePathName.addAll(new HashSet(downloadDirectory(ftpClient, "", "", ftpLocalRelativePath)));
    }
    getOut().println("END Import file(s) from FTP.");
    return filesRelativePathName;
}