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

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

Introduction

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

Prototype

public boolean makeDirectory(String pathname) throws IOException 

Source Link

Document

Creates a new subdirectory on the FTP server in the current directory (if a relative pathname is given) or where specified (if an absolute pathname is given).

Usage

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Creates all parent directories specified in a complete relative
 * pathname. Attempts to create existing directories will not cause
 * errors./*  w ww .j av a2 s  .c  om*/
 *
 * @param ftp the FTP client instance to use to execute FTP actions on
 *        the remote server.
 * @param filename the name of the file whose parents should be created.
 * @throws IOException under non documented circumstances
 * @throws BuildException if it is impossible to cd to a remote directory
 *
 */
protected void createParents(FTPClient ftp, String filename) throws IOException, BuildException {

    File dir = new File(filename);
    if (dirCache.contains(dir)) {
        return;
    }

    Vector parents = new Vector();
    String dirname;

    while ((dirname = dir.getParent()) != null) {
        File checkDir = new File(dirname);
        if (dirCache.contains(checkDir)) {
            break;
        }
        dir = checkDir;
        parents.addElement(dir);
    }

    // find first non cached dir
    int i = parents.size() - 1;

    if (i >= 0) {
        String cwd = ftp.printWorkingDirectory();
        String parent = dir.getParent();
        if (parent != null) {
            if (!ftp.changeWorkingDirectory(resolveFile(parent))) {
                throw new BuildException("could not change to " + "directory: " + ftp.getReplyString());
            }
        }

        while (i >= 0) {
            dir = (File) parents.elementAt(i--);
            // check if dir exists by trying to change into it.
            if (!ftp.changeWorkingDirectory(dir.getName())) {
                // could not change to it - try to create it
                log("creating remote directory " + resolveFile(dir.getPath()), Project.MSG_VERBOSE);
                if (!ftp.makeDirectory(dir.getName())) {
                    handleMkDirFailure(ftp);
                }
                if (!ftp.changeWorkingDirectory(dir.getName())) {
                    throw new BuildException("could not change to " + "directory: " + ftp.getReplyString());
                }
            }
            dirCache.add(dir);
        }
        ftp.changeWorkingDirectory(cwd);
    }
}

From source file:hydrograph.engine.spark.datasource.utils.FTPUtil.java

public void upload(RunFileTransferEntity runFileTransferEntity) {
    log.debug("Start FTPUtil upload");

    FTPClient ftpClient = new FTPClient();
    ftpClient.enterLocalPassiveMode();//from   www  .  jav  a 2s.  c  o  m
    ftpClient.setBufferSize(1024000);

    int retryAttempt = runFileTransferEntity.getRetryAttempt();
    int attemptCount = 1;
    int i = 0;

    InputStream inputStream = null;
    boolean login = false;
    File filecheck = new File(runFileTransferEntity.getInputFilePath());
    log.info("input file name" + filecheck.getName());
    if (runFileTransferEntity.getFailOnError()) {
        if (!(filecheck.isFile() || filecheck.isDirectory())
                && !(runFileTransferEntity.getInputFilePath().contains("hdfs://"))) {
            log.error("Invalid input file path. Please provide valid input file path.");
            throw new FTPUtilException("Invalid input file path");
        }
    }

    boolean done = false;
    for (i = 0; i < retryAttempt; i++) {
        try {
            log.info("Connection attempt: " + (i + 1));
            if (runFileTransferEntity.getTimeOut() != 0)
                if (runFileTransferEntity.getEncoding() != null)
                    ftpClient.setControlEncoding(runFileTransferEntity.getEncoding());
            ftpClient.setConnectTimeout(runFileTransferEntity.getTimeOut());
            log.debug("connection details: " + "/n" + "Username: " + runFileTransferEntity.getUserName() + "/n"
                    + "HostName " + runFileTransferEntity.getHostName() + "/n" + "Portno"
                    + runFileTransferEntity.getPortNo());
            ftpClient.connect(runFileTransferEntity.getHostName(), runFileTransferEntity.getPortNo());
            login = ftpClient.login(runFileTransferEntity.getUserName(), runFileTransferEntity.getPassword());
            if (!login) {
                log.error("Invalid FTP details provided. Please provide correct FTP details.");
                throw new FTPUtilException("Invalid FTP details");
            }
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (runFileTransferEntity.getInputFilePath().contains("hdfs://")) {
                log.debug("Processing for HDFS input file path");
                String inputPath = runFileTransferEntity.getInputFilePath();

                String s1 = inputPath.substring(7, inputPath.length());

                String s2 = s1.substring(0, s1.indexOf("/"));

                int index = runFileTransferEntity.getInputFilePath()
                        .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/');

                String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1);

                File f = new File("/tmp");
                if (!f.exists())
                    f.mkdir();
                Configuration conf = new Configuration();
                conf.set("fs.defaultFS", "hdfs://" + s2);
                FileSystem hdfsFileSystem = FileSystem.get(conf);
                Path local = new Path("/tmp");
                String s = inputPath.substring(7, inputPath.length());
                String hdfspath = s.substring(s.indexOf("/"), s.length());
                File dir = new File(hdfspath);
                Random ran = new Random();
                String tempFolder = "ftp_sftp_" + System.nanoTime() + "_" + ran.nextInt(1000);
                File dirs = new File("/tmp/" + tempFolder);
                boolean success = dirs.mkdirs();
                if (hdfsFileSystem.isDirectory(new Path(hdfspath))) {
                    log.debug("Provided HDFS input path is for directory.");
                    InputStream is = null;
                    OutputStream os = null;
                    String localDirectory = hdfspath.substring(hdfspath.lastIndexOf("/") + 1);
                    FileStatus[] fileStatus = hdfsFileSystem
                            .listStatus(new Path(runFileTransferEntity.getInputFilePath()));
                    Path[] paths = FileUtil.stat2Paths(fileStatus);
                    try {
                        String folderName = hdfspath.substring(hdfspath.lastIndexOf("/") + 1);
                        Path hdfs = new Path(hdfspath);
                        for (Path file : paths) {
                            is = hdfsFileSystem.open(file);
                            os = new BufferedOutputStream(
                                    new FileOutputStream(dirs + "" + File.separatorChar + file.getName()));
                            IOUtils.copyBytes(is, os, conf);
                        }
                        ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath()
                                .replaceAll(Matcher.quoteReplacement("\\"), "/"));
                        ftpClient.removeDirectory(folderName);
                        ftpClient.makeDirectory(folderName);
                        ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath().replaceAll(
                                Matcher.quoteReplacement("\\"), "/") + File.separatorChar + folderName);
                        for (File files : dirs.listFiles()) {

                            if (files.isFile())
                                ftpClient.storeFile(files.getName().toString(),
                                        new BufferedInputStream(new FileInputStream(files)));

                        }
                    } catch (IOException e) {
                        log.error("Failed while doing FTP file", e);
                        //throw e;
                    } finally {
                        IOUtils.closeStream(is);
                        IOUtils.closeStream(os);
                        if (dirs != null) {
                            FileUtils.deleteDirectory(dirs);
                        }
                    }
                } else {
                    try {
                        Path hdfs = new Path(hdfspath);
                        hdfsFileSystem.copyToLocalFile(false, hdfs, local);
                        inputStream = new FileInputStream(dirs + file_name);
                        ftpClient.storeFile(file_name, new BufferedInputStream(inputStream));
                    } catch (Exception e) {
                        log.error("Failed while doing FTP file", e);
                        throw new FTPUtilException("Failed while doing FTP file", e);
                    } finally {
                        FileUtils.deleteDirectory(dirs);
                    }
                }
            } else {
                java.nio.file.Path file = new File(runFileTransferEntity.getInputFilePath()).toPath();
                if (Files.isDirectory(file)) {
                    log.debug("Provided input file path is for directory");
                    File dir = new File(runFileTransferEntity.getInputFilePath());
                    String folderName = new File(runFileTransferEntity.getInputFilePath()).getName();
                    ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath()
                            .replaceAll(Matcher.quoteReplacement("\\"), "/"));
                    try {
                        ftpClient.removeDirectory(folderName);
                    } catch (IOException e) {
                        log.error("Failed while doing FTP file", e);
                        throw new FTPUtilException("Failed while doing FTP file", e);
                    }
                    ftpClient.makeDirectory(folderName);

                    ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath()
                            .replaceAll(Matcher.quoteReplacement("\\"), "/") + "/" + folderName);
                    for (File files : dir.listFiles()) {

                        if (files.isFile())
                            ftpClient.storeFile(files.getName().toString(),
                                    new BufferedInputStream(new FileInputStream(files)));
                    }
                } else {

                    inputStream = new FileInputStream(runFileTransferEntity.getInputFilePath());
                    ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath()
                            .replaceAll(Matcher.quoteReplacement("\\"), "/"));
                    int index = runFileTransferEntity.getInputFilePath()
                            .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/');
                    String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1);
                    ftpClient.storeFile(file_name, new BufferedInputStream(inputStream));
                }

            }
        } catch (Exception e) {
            log.error("Failed while doing FTP file", e);
            if (!login && runFileTransferEntity.getFailOnError()) {
                throw new FTPUtilException("Invalid FTP details");
            }
            try {
                Thread.sleep(runFileTransferEntity.getRetryAfterDuration());
            } catch (Exception e1) {
                log.error("Failed while sleeping for retry duration", e1);
            }
            continue;
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException ioe) {

            }
        }
        done = true;
        break;
    }

    try {
        if (ftpClient != null) {
            ftpClient.logout();
            ftpClient.disconnect();

        }
    } catch (Exception e) {
        log.error("Failed while clossing the connection", e);
    } catch (Error e) {
        log.error("Failed while clossing the connection", e);
        //throw new RuntimeException(e);
    }

    if (runFileTransferEntity.getFailOnError() && !done) {
        log.error("File transfer failed");
        throw new FTPUtilException("File transfer failed");
    } else if (!done) {
        log.error("File transfer failed but mentioned fail on error as false");
    }
    log.debug("Finished FTPUtil upload");
}

From source file:net.yacy.grid.io.assets.FTPStorageFactory.java

public FTPStorageFactory(String server, int port, String username, String password, boolean deleteafterread)
        throws IOException {
    this.server = server;
    this.username = username == null ? "" : username;
    this.password = password == null ? "" : password;
    this.port = port;
    this.deleteafterread = deleteafterread;

    this.ftpClient = new Storage<byte[]>() {

        @Override/*w  w  w  . ja va  2s  . c  o  m*/
        public void checkConnection() throws IOException {
            return;
        }

        private FTPClient initConnection() throws IOException {
            FTPClient ftp = new FTPClient();
            ftp.setDataTimeout(3000);
            ftp.setConnectTimeout(20000);
            if (FTPStorageFactory.this.port < 0 || FTPStorageFactory.this.port == DEFAULT_PORT) {
                ftp.connect(FTPStorageFactory.this.server);
            } else {
                ftp.connect(FTPStorageFactory.this.server, FTPStorageFactory.this.port);
            }
            ftp.enterLocalPassiveMode(); // the server opens a data port to which the client conducts data transfers
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
                throw new IOException("bad connection to ftp server: " + reply);
            }
            if (!ftp.login(FTPStorageFactory.this.username, FTPStorageFactory.this.password)) {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
                throw new IOException("login failure");
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.setBufferSize(8192);
            return ftp;
        }

        @Override
        public StorageFactory<byte[]> store(String path, byte[] asset) throws IOException {
            long t0 = System.currentTimeMillis();
            FTPClient ftp = initConnection();
            try {
                long t1 = System.currentTimeMillis();
                String file = cdPath(ftp, path);
                long t2 = System.currentTimeMillis();
                ftp.enterLocalPassiveMode();
                boolean success = ftp.storeFile(file, new ByteArrayInputStream(asset));
                long t3 = System.currentTimeMillis();
                if (!success)
                    throw new IOException("storage to path " + path + " was not successful (storeFile=false)");
                Data.logger.debug("FTPStorageFactory.store ftp store successfull: check connection = "
                        + (t1 - t0) + ", cdPath = " + (t2 - t1) + ", store = " + (t3 - t2));
            } catch (IOException e) {
                throw e;
            } finally {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
            }
            return FTPStorageFactory.this;
        }

        @Override
        public Asset<byte[]> load(String path) throws IOException {
            FTPClient ftp = initConnection();
            ByteArrayOutputStream baos = null;
            byte[] b = null;
            try {
                String file = cdPath(ftp, path);
                baos = new ByteArrayOutputStream();
                ftp.retrieveFile(file, baos);
                b = baos.toByteArray();
                if (FTPStorageFactory.this.deleteafterread)
                    try {
                        boolean deleted = ftp.deleteFile(file);
                        FTPFile[] remaining = ftp.listFiles();
                        if (remaining.length == 0) {
                            ftp.cwd("/");
                            if (path.startsWith("/"))
                                path = path.substring(1);
                            int p = path.indexOf('/');
                            if (p > 0)
                                path = path.substring(0, p);
                            ftp.removeDirectory(path);
                        }
                    } catch (Throwable e) {
                        Data.logger.warn("FTPStorageFactory.load failed to remove asset " + path, e);
                    }
            } catch (IOException e) {
                throw e;
            } finally {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
            }
            return new Asset<byte[]>(FTPStorageFactory.this, b);
        }

        @Override
        public void close() {
        }

        private String cdPath(FTPClient ftp, String path) throws IOException {
            int success_code = ftp.cwd("/");
            if (success_code >= 300)
                throw new IOException("cannot cd into " + path + ": " + success_code);
            if (path.length() == 0 || path.equals("/"))
                return "";
            if (path.charAt(0) == '/')
                path = path.substring(1); // we consider that all paths are absolute to / (home)
            int p;
            while ((p = path.indexOf('/')) > 0) {
                String dir = path.substring(0, p);
                int code = ftp.cwd(dir);
                if (code >= 300) {
                    // path may not exist, try to create the path
                    boolean success = ftp.makeDirectory(dir);
                    if (!success)
                        throw new IOException("unable to create directory " + dir + " for path " + path);
                    code = ftp.cwd(dir);
                    if (code >= 300)
                        throw new IOException("unable to cwd into directory " + dir + " for path " + path);
                }
                path = path.substring(p + 1);
            }
            return path;
        }
    };
}

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

/**
 * Test CRUD for FTP server//from w w w  .  j a  v  a 2 s.  c o m
 *
 * @throws Exception
 */
public void testCRUD() throws Exception {
    final String PATH1 = "FTPServerTest";
    final String PATH2 = "Second part";

    logger.debug("Start testFTPCRUD");

    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")));

        // 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
        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();

        // 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.alfresco.filesys.FTPServerTest.java

/**
 * Test of obscure path names in the FTP server
 * //from w ww  .  j  a  v a2 s.  c  o  m
 * 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/*  w  ww  .j  av a 2  s .  co  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 .ja  v 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.apache.ftpserver.clienttests.SiteTest.java

public void testSiteStat() throws Exception {
    // reboot server to clear stats
    server.stop();//from   w ww  .  jav  a  2s .com
    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  . j a  v a 2 s.  co  m
private boolean mkdirs(FTPClient client, Path file, FsPermission permission) throws IOException {
    boolean created = true;
    Path workDir = new Path(client.printWorkingDirectory());
    Path absolute = makeAbsolute(workDir, file);
    String pathName = absolute.getName();
    if (!exists(client, absolute)) {
        Path parent = absolute.getParent();
        created = (parent == null || mkdirs(client, parent, FsPermission.getDefault()));
        if (created) {
            String parentDir = parent.toUri().getPath();
            client.changeWorkingDirectory(parentDir);
            created = created & client.makeDirectory(pathName);
        }
    } else if (isFile(client, absolute)) {
        throw new IOException(String.format("Can't make directory for path %s since it is a file.", absolute));
    }
    return created;
}

From source file:org.apache.nifi.processors.standard.util.FTPUtils.java

/**
 * Handles the logic required to change to the given directory RELATIVE TO THE CURRENT DIRECTORY which can include creating new directories needed.
 *
 * This will first attempt to change to the full path of the given directory outright. If that fails, then it will attempt to change from the top of the tree of the given directory all the way
 * down to the final leaf node of the given directory.
 *
 * @param client - the ftp client with an already active connection
 * @param dirPath - the path to change or create directories to
 * @param createDirs - if true will attempt to create any missing directories
 * @param processor - used solely for targeting logging output.
 * @throws IOException if any access problem occurs
 *//*w  w w .  j  av  a2s  .  com*/
public static void changeWorkingDirectory(final FTPClient client, final String dirPath,
        final boolean createDirs, final Processor processor) throws IOException {
    final String currentWorkingDirectory = client.printWorkingDirectory();
    final File dir = new File(dirPath);
    logger.debug(processor + " attempting to change directory from " + currentWorkingDirectory + " to "
            + dir.getPath());
    boolean dirExists = false;
    final String forwardPaths = dir.getPath().replaceAll(Matcher.quoteReplacement("\\"),
            Matcher.quoteReplacement("/"));
    //always use forward paths for long string attempt
    try {
        dirExists = client.changeWorkingDirectory(forwardPaths);
        if (dirExists) {
            logger.debug(processor + " changed working directory to '" + forwardPaths + "' from '"
                    + currentWorkingDirectory + "'");
        } else {
            logger.debug(processor + " could not change directory to '" + forwardPaths + "' from '"
                    + currentWorkingDirectory + "' so trying the hard way.");
        }
    } catch (final IOException ioe) {
        logger.debug(processor + " could not change directory to '" + forwardPaths + "' from '"
                + currentWorkingDirectory + "' so trying the hard way.");
    }
    if (!dirExists) { //couldn't navigate directly...begin hard work
        final Deque<String> stack = new LinkedList<>();
        File fakeFile = new File(dir.getPath());
        do {
            stack.push(fakeFile.getName());
        } while ((fakeFile = fakeFile.getParentFile()) != null);

        String dirName = null;
        while ((dirName = stack.peek()) != null) {
            stack.pop();
            //find out if exists, if not make it if configured to do so or throw exception
            dirName = ("".equals(dirName.trim())) ? "/" : dirName;
            boolean exists = false;
            try {
                exists = client.changeWorkingDirectory(dirName);
            } catch (final IOException ioe) {
                exists = false;
            }
            if (!exists && createDirs) {
                logger.debug(processor + " creating new directory and changing to it " + dirName);
                client.makeDirectory(dirName);
                if (!(client.makeDirectory(dirName) || client.changeWorkingDirectory(dirName))) {
                    throw new IOException(
                            processor + " could not create and change to newly created directory " + dirName);
                } else {
                    logger.debug(processor + " successfully changed working directory to " + dirName);
                }
            } else if (!exists) {
                throw new IOException(processor + " could not change directory to '" + dirName + "' from '"
                        + currentWorkingDirectory + "'");
            }
        }
    }
}