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

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

Introduction

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

Prototype

public boolean removeDirectory(String pathname) throws IOException 

Source Link

Document

Removes a directory on the FTP server (if empty).

Usage

From source file:org.alfresco.filesys.FTPServerTest.java

/**
 * Test of obscure path names in the FTP server
 * //from w w w . j  av  a2  s  .com
 * RFC959 states that paths are constructed thus...
 * <string> ::= <char> | <char><string>
 * <pathname> ::= <string>
 * <char> ::= any of the 128 ASCII characters except <CR> and <LF>
 *       
 *  So we need to check how high characters and problematic are encoded     
 */
public void testPathNames() throws Exception {

    logger.debug("Start testPathNames");

    FTPClient ftp = connectClient();

    String PATH1 = "testPathNames";

    try {
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            fail("FTP server refused connection.");
        }

        boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN);
        assertTrue("admin login successful", login);

        reply = ftp.cwd("/Alfresco/User*Homes");
        assertTrue(FTPReply.isPositiveCompletion(reply));

        // Delete the root directory in case it was left over from a previous test run
        try {
            ftp.removeDirectory(PATH1);
        } catch (IOException e) {
            // ignore this error
        }

        // make root directory for this test
        boolean success = ftp.makeDirectory(PATH1);
        assertTrue("unable to make directory:" + PATH1, success);

        success = ftp.changeWorkingDirectory(PATH1);
        assertTrue("unable to change to working directory:" + PATH1, success);

        assertTrue("with a space", ftp.makeDirectory("test space"));
        assertTrue("with exclamation", ftp.makeDirectory("space!"));
        assertTrue("with dollar", ftp.makeDirectory("space$"));
        assertTrue("with brackets", ftp.makeDirectory("space()"));
        assertTrue("with hash curley  brackets", ftp.makeDirectory("space{}"));

        //Pound sign U+00A3
        //Yen Sign U+00A5
        //Capital Omega U+03A9

        assertTrue("with pound sign", ftp.makeDirectory("pound \u00A3.world"));
        assertTrue("with yen sign", ftp.makeDirectory("yen \u00A5.world"));

        // Test steps that do not work
        // assertTrue("with omega", ftp.makeDirectory("omega \u03A9.world"));
        // assertTrue("with obscure ASCII chars", ftp.makeDirectory("?/.,<>"));    
    } finally {
        // clean up tree if left over from previous run

        ftp.disconnect();
    }

}

From source file:org.alfresco.filesys.FTPServerTest.java

/**
 * Test of rename case ALF-20584/*from www.  j  a v a2 s .  c o  m*/
 * 
        
 */
public void testRenameCase() throws Exception {

    logger.debug("Start testRenameCase");

    FTPClient ftp = connectClient();

    String PATH1 = "testRenameCase";

    try {
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            fail("FTP server refused connection.");
        }

        boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN);
        assertTrue("admin login successful", login);

        reply = ftp.cwd("/Alfresco/User*Homes");
        assertTrue(FTPReply.isPositiveCompletion(reply));

        // Delete the root directory in case it was left over from a previous test run
        try {
            ftp.removeDirectory(PATH1);
        } catch (IOException e) {
            // ignore this error
        }

        // make root directory for this test
        boolean success = ftp.makeDirectory(PATH1);
        assertTrue("unable to make directory:" + PATH1, success);

        ftp.cwd(PATH1);

        String FILE1_CONTENT_2 = "That's how it is says Pooh!";
        ftp.storeFile("FileA.txt", new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));

        assertTrue("unable to rename", ftp.rename("FileA.txt", "FILEA.TXT"));

    } finally {
        // clean up tree if left over from previous run

        ftp.disconnect();
    }

}

From source file:org.alfresco.filesys.FTPServerTest.java

/**
 * Test Setting the modification time FTP server
 *
 * @throws Exception//from w w  w.j av  a  2  s.c o  m
 */
public void testModificationTime() throws Exception {
    final String PATH1 = "FTPServerTest";
    final String PATH2 = "ModificationTime";

    logger.debug("Start testModificationTime");

    FTPClient ftp = connectClient();

    try {
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            fail("FTP server refused connection.");
        }

        boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN);
        assertTrue("admin login successful", login);

        reply = ftp.cwd("/Alfresco/User Homes");
        assertTrue(FTPReply.isPositiveCompletion(reply));

        // Delete the root directory in case it was left over from a previous test run
        try {
            ftp.removeDirectory(PATH1);
        } catch (IOException e) {
            // ignore this error
        }

        // make root directory
        ftp.makeDirectory(PATH1);
        ftp.cwd(PATH1);

        // make sub-directory in new directory
        ftp.makeDirectory(PATH2);
        ftp.cwd(PATH2);

        // List the files in the new directory
        FTPFile[] files = ftp.listFiles();
        assertTrue("files not empty", files.length == 0);

        // Create a file
        String FILE1_CONTENT_1 = "test file 1 content";
        String FILE1_NAME = "testFile1.txt";
        ftp.appendFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8")));

        String pathname = "/Alfresco/User Homes" + "/" + PATH1 + "/" + PATH2 + "/" + FILE1_NAME;

        logger.debug("set modification time");
        // YYYYMMDDhhmmss Time set to 2012 August 30 12:39:05
        String olympicTime = "20120830123905";
        ftp.setModificationTime(pathname, olympicTime);

        String extractedTime = ftp.getModificationTime(pathname);
        // Feature of the commons ftp library ExtractedTime has a "status code" first and is followed by newline chars

        assertTrue("time not set correctly by explicit set time", extractedTime.contains(olympicTime));

        // Get the new file
        FTPFile[] files2 = ftp.listFiles();
        assertTrue("files not one", files2.length == 1);

        InputStream is = ftp.retrieveFileStream(FILE1_NAME);

        String content = inputStreamToString(is);
        assertEquals("Content is not as expected", content, FILE1_CONTENT_1);
        ftp.completePendingCommand();

        // Update the file contents without setting time directly
        String FILE1_CONTENT_2 = "That's how it is says Pooh!";
        ftp.storeFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));

        InputStream is2 = ftp.retrieveFileStream(FILE1_NAME);

        String content2 = inputStreamToString(is2);
        assertEquals("Content is not as expected", FILE1_CONTENT_2, content2);
        ftp.completePendingCommand();

        extractedTime = ftp.getModificationTime(pathname);

        assertFalse("time not moved on if time not explicitly set", extractedTime.contains(olympicTime));

        // now delete the file we have been using.
        assertTrue(ftp.deleteFile(FILE1_NAME));

        // negative test - file should have gone now.
        assertFalse(ftp.deleteFile(FILE1_NAME));

    } finally {
        // clean up tree if left over from previous run

        ftp.disconnect();
    }
}

From source file:org.alinous.ftp.FtpManager.java

public void removeDirectory(String sessionId, String pathname) throws IOException {
    FTPClient ftp = this.instances.get(sessionId).getFtp();
    ftp.removeDirectory(pathname);
}

From source file:org.apache.ftpserver.clienttests.SiteTest.java

public void testSiteStat() throws Exception {
    // reboot server to clear stats
    server.stop();//w  ww. ja v  a 2 s . c o m
    initServer();

    // let's generate some stats
    FTPClient client1 = new FTPClient();
    client1.connect("localhost", getListenerPort());

    assertTrue(client1.login(ADMIN_USERNAME, ADMIN_PASSWORD));
    assertTrue(client1.makeDirectory("foo"));
    assertTrue(client1.makeDirectory("foo2"));
    assertTrue(client1.removeDirectory("foo2"));
    assertTrue(client1.storeFile(TEST_FILENAME, new ByteArrayInputStream(TESTDATA)));
    assertTrue(client1.storeFile(TEST_FILENAME, new ByteArrayInputStream(TESTDATA)));
    assertTrue(client1.retrieveFile(TEST_FILENAME, new ByteArrayOutputStream()));
    assertTrue(client1.deleteFile(TEST_FILENAME));

    assertTrue(client1.logout());
    client1.disconnect();

    FTPClient client2 = new FTPClient();
    client2.connect("localhost", getListenerPort());

    assertTrue(client2.login(ANONYMOUS_USERNAME, ANONYMOUS_PASSWORD));
    // done setting up stats

    client.connect("localhost", getListenerPort());
    client.login(ADMIN_USERNAME, ADMIN_PASSWORD);

    client.sendCommand("SITE STAT");
    String[] siteReplies = client.getReplyString().split("\r\n");

    assertEquals("200-", siteReplies[0]);

    String pattern = "Start Time               : " + TIMESTAMP_PATTERN;
    assertTrue(Pattern.matches(pattern, siteReplies[1]));

    assertTrue(Pattern.matches("File Upload Number       : 2", siteReplies[2]));
    assertTrue(Pattern.matches("File Download Number     : 1", siteReplies[3]));
    assertTrue(Pattern.matches("File Delete Number       : 1", siteReplies[4]));
    assertTrue(Pattern.matches("File Upload Bytes        : 16", siteReplies[5]));
    assertTrue(Pattern.matches("File Download Bytes      : 8", siteReplies[6]));
    assertTrue(Pattern.matches("Directory Create Number  : 2", siteReplies[7]));
    assertTrue(Pattern.matches("Directory Remove Number  : 1", siteReplies[8]));
    assertTrue(Pattern.matches("Current Logins           : 2", siteReplies[9]));
    assertTrue(Pattern.matches("Total Logins             : 3", siteReplies[10]));
    assertTrue(Pattern.matches("Current Anonymous Logins : 1", siteReplies[11]));
    assertTrue(Pattern.matches("Total Anonymous Logins   : 1", siteReplies[12]));
    assertTrue(Pattern.matches("Current Connections      : 2", siteReplies[13]));
    assertTrue(Pattern.matches("200 Total Connections        : 3", siteReplies[14]));
}

From source file:org.apache.hadoop.fs.ftp.FTPFileSystem.java

/**
 * Convenience method, so that we don't open a new connection when using this
 * method from within another method. Otherwise every API invocation incurs
 * the overhead of opening/closing a TCP connection.
 *//*from w w  w . ja v  a  2  s  .  c o  m*/
private boolean delete(FTPClient client, Path file, boolean recursive) throws IOException {
    Path workDir = new Path(client.printWorkingDirectory());
    Path absolute = makeAbsolute(workDir, file);
    String pathName = absolute.toUri().getPath();
    FileStatus fileStat = getFileStatus(client, absolute);
    if (!fileStat.isDir()) {
        return client.deleteFile(pathName);
    }
    FileStatus[] dirEntries = listStatus(client, absolute);
    if (dirEntries != null && dirEntries.length > 0 && !(recursive)) {
        throw new IOException("Directory: " + file + " is not empty.");
    }
    if (dirEntries != null) {
        for (int i = 0; i < dirEntries.length; i++) {
            delete(client, new Path(absolute, dirEntries[i].getPath()), recursive);
        }
    }
    return client.removeDirectory(pathName);
}

From source file:org.apache.tools.ant.taskdefs.optional.net.FTPTaskMirrorImpl.java

/**
 * Delete a directory, if empty, from the remote host.
 * @param ftp ftp client/*from   www .ja  v  a 2  s  . c  o  m*/
 * @param dirname directory to delete
 * @throws IOException  in unknown circumstances
 * @throws BuildException if skipFailedTransfers is set to false
 * and the deletion could not be done
 */
protected void rmDir(FTPClient ftp, String dirname) throws IOException, BuildException {
    if (task.isVerbose()) {
        task.log("removing " + dirname);
    }

    if (!ftp.removeDirectory(resolveFile(dirname))) {
        String s = "could not remove directory: " + ftp.getReplyString();

        if (task.isSkipFailedTransfers()) {
            task.log(s, Project.MSG_WARN);
            skipped++;
        } else {
            throw new BuildException(s);
        }
    } else {
        task.log("Directory " + dirname + " removed from " + task.getServer(), Project.MSG_VERBOSE);
        transferred++;
    }
}

From source file:org.limy.common.util.FtpUtils.java

/**
 * ???/* ww  w. ja  va2 s.  c o  m*/
 * @param client FTP
 * @param relativePath ??
 * @return ????
 * @throws IOException I/O
 */
public static boolean deleteDir(FTPClient client, String relativePath) throws IOException {

    return client.removeDirectory(relativePath);
}

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//from  w w  w .ja  v  a  2 s  .  co  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:ro.kuberam.libs.java.ftclient.FTP.FTP.java

public boolean deleteResource(Object abstractConnection, String remoteResourcePath) throws Exception {
    long startTime = new Date().getTime();
    FTPClient FTPconnection = (FTPClient) abstractConnection;
    if (!FTPconnection.isConnected()) {
        throw new Exception(ErrorMessages.err_FTC002);
    }/*from  w  ww .  j  a  v  a 2  s  .  c  o  m*/

    Boolean result = true;
    List<Object> FTPconnectionObject = _checkResourcePath(FTPconnection, remoteResourcePath, "delete-resource",
            checkIsDirectory(remoteResourcePath));

    try {
        if ((Boolean) FTPconnectionObject.get(0)) {
            FTPconnection.removeDirectory(remoteResourcePath);
            log.info("The FTP sub-module deleted the directory in " + (new Date().getTime() - startTime)
                    + " ms.");
        } else {
            FTPconnection.deleteFile(remoteResourcePath);
            log.info("The FTP sub-module deleted the file in " + (new Date().getTime() - startTime) + " ms.");
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        result = false;
    }

    // if (!FTPconnection.completePendingCommand()) {
    // throw new Exception("err:FTC007: The current operation failed.");
    // }

    log.info("The FTP sub-module deleted the resource '" + remoteResourcePath + "' in "
            + (new Date().getTime() - startTime) + " ms.");

    return result;
}