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.alfresco.bm.file.FtpTestFileService.java

/**
 * Does a listing of files on the FTP server
 *//*  w  w  w . java  2s.  c o m*/
@Override
protected List<FileData> listRemoteFiles() {
    // Get a list of files from the FTP server
    FTPClient ftp = null;
    FTPFile[] ftpFiles = new FTPFile[0];
    try {
        ftp = getFTPClient();
        if (!ftp.changeWorkingDirectory(ftpPath)) {
            throw new IOException("Failed to change directory (leading '/' could be a problem): " + ftpPath);
        }
        ftpFiles = ftp.listFiles();
    } catch (IOException e) {
        throw new RuntimeException("FTP file listing failed: " + this, e);
    } finally {
        try {
            if (null != ftp) {
                ftp.logout();
                ftp.disconnect();
            }
        } catch (IOException e) {
            logger.warn("Failed to close FTP connection: " + e.getMessage());
        }
    }
    // Index each of the files
    List<FileData> remoteFileDatas = new ArrayList<FileData>(ftpFiles.length);
    for (FTPFile ftpFile : ftpFiles) {
        String ftpFilename = ftpFile.getName();
        // Watch out for . and ..
        if (ftpFilename.equals(".") || ftpFilename.equals("..")) {
            continue;
        }
        String ftpExtension = FileData.getExtension(ftpFilename);
        long ftpSize = ftpFile.getSize();

        FileData remoteFileData = new FileData();
        remoteFileData.setRemoteName(ftpFilename);
        remoteFileData.setExtension(ftpExtension);
        remoteFileData.setSize(ftpSize);

        remoteFileDatas.add(remoteFileData);
    }
    // Done
    return remoteFileDatas;
}

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

/**
 * Test of obscure path names in the FTP server
 * //from  ww  w. j  a v a2s  .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

/**
 * Create a user other than "admin" who has access to a set of files. 
 * /*from   w  w w.j av a  2 s.co m*/
 * Create a folder containing test.docx as user one
 * Update that file as user two.
 * Check user one can see user two's changes.
 * 
 * @throws Exception
 */
public void testTwoUserUpdate() throws Exception {
    logger.debug("Start testFTPConnect");

    final String TEST_DIR = "/Alfresco/User Homes/" + USER_ONE;

    FTPClient ftpOne = connectClient();
    FTPClient ftpTwo = connectClient();
    try {
        int reply = ftpOne.getReplyCode();

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

        reply = ftpTwo.getReplyCode();

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

        boolean login = ftpOne.login(USER_ONE, PASSWORD_ONE);
        assertTrue("user one login not successful", login);

        login = ftpTwo.login(USER_TWO, PASSWORD_TWO);
        assertTrue("user two login not successful", login);

        boolean success = ftpOne.changeWorkingDirectory("Alfresco");
        assertTrue("user one unable to cd to Alfreco", success);
        success = ftpOne.changeWorkingDirectory("User*Homes");
        assertTrue("user one unable to cd to User*Homes", success);
        success = ftpOne.changeWorkingDirectory(USER_ONE);
        assertTrue("user one unable to cd to " + USER_ONE, success);

        success = ftpTwo.changeWorkingDirectory("Alfresco");
        assertTrue("user two unable to cd to Alfreco", success);
        success = ftpTwo.changeWorkingDirectory("User*Homes");
        assertTrue("user two unable to cd to User*Homes", success);
        success = ftpTwo.changeWorkingDirectory(USER_ONE);
        assertTrue("user two unable to cd " + USER_ONE, success);

        // Create a file as user one
        String FILE1_CONTENT_1 = "test file 1 content";
        String FILE1_NAME = "test.docx";
        success = ftpOne.appendFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_1.getBytes("UTF-8")));
        assertTrue("user one unable to append file", success);

        // Update the file as user two
        String FILE1_CONTENT_2 = "test file content updated";
        success = ftpTwo.storeFile(FILE1_NAME, new ByteArrayInputStream(FILE1_CONTENT_2.getBytes("UTF-8")));
        assertTrue("user two unable to append file", success);

        // User one should read user2's content
        InputStream is1 = ftpOne.retrieveFileStream(FILE1_NAME);
        assertNotNull("is1 is null", is1);
        String content1 = inputStreamToString(is1);
        assertEquals("Content is not as expected", FILE1_CONTENT_2, content1);
        ftpOne.completePendingCommand();

        // User two should read user2's content
        InputStream is2 = ftpTwo.retrieveFileStream(FILE1_NAME);
        assertNotNull("is2 is null", is2);
        String content2 = inputStreamToString(is2);
        assertEquals("Content is not as expected", FILE1_CONTENT_2, content2);
        ftpTwo.completePendingCommand();
        logger.debug("Test finished");

    } finally {
        ftpOne.dele(TEST_DIR);
        if (ftpOne != null) {
            ftpOne.disconnect();
        }
        if (ftpTwo != null) {
            ftpTwo.disconnect();
        }
    }

}

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

/**
 * Test a quota failue exception over FTP.
 * A file should not exist after a create and quota exception. 
 *//*from www  .j  ava  2  s  .c  o m*/
public void testFtpQuotaAndFtp() throws Exception {
    // Enable usages
    ContentUsageImpl contentUsage = (ContentUsageImpl) applicationContext.getBean("contentUsageImpl");
    contentUsage.setEnabled(true);
    contentUsage.init();
    UserUsageTrackingComponent userUsageTrackingComponent = (UserUsageTrackingComponent) applicationContext
            .getBean("userUsageTrackingComponent");
    userUsageTrackingComponent.setEnabled(true);
    userUsageTrackingComponent.bootstrapInternal();

    final String TEST_DIR = "/Alfresco/User Homes/" + USER_THREE;

    FTPClient ftpOne = connectClient();
    try {
        int reply = ftpOne.getReplyCode();

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

        boolean login = ftpOne.login(USER_THREE, PASSWORD_THREE);
        assertTrue("user three login not successful", login);

        boolean success = ftpOne.changeWorkingDirectory("Alfresco");
        assertTrue("user three unable to cd to Alfreco", success);
        success = ftpOne.changeWorkingDirectory("User*Homes");
        assertTrue("user one unable to cd to User*Homes", success);
        success = ftpOne.changeWorkingDirectory(USER_THREE);
        assertTrue("user one unable to cd to " + USER_THREE, success);

        /**
         * Create a file as user three which is bigger than the quota
         */
        String FILE3_CONTENT_3 = "test file 3 content that needs to be greater than 100 bytes to result in a quota exception being thrown";
        String FILE1_NAME = "test.docx";

        // Should not be success
        success = ftpOne.appendFile(FILE1_NAME, new ByteArrayInputStream(FILE3_CONTENT_3.getBytes("UTF-8")));
        assertFalse("user one can ignore quota", success);

        boolean deleted = ftpOne.deleteFile(FILE1_NAME);
        assertFalse("quota exception expected", deleted);

        logger.debug("test done");

    } finally {
        // Disable usages
        contentUsage.setEnabled(false);
        contentUsage.init();
        userUsageTrackingComponent.setEnabled(false);
        userUsageTrackingComponent.bootstrapInternal();

        ftpOne.dele(TEST_DIR);
        if (ftpOne != null) {
            ftpOne.disconnect();
        }
    }

}

From source file:org.apache.activemq.blob.FTPBlobDownloadStrategy.java

public InputStream getInputStream(ActiveMQBlobMessage message) throws IOException, JMSException {
    url = message.getURL();//from w w  w.  j  ava 2s  . c o  m
    final FTPClient ftp = createFTP();
    String path = url.getPath();
    String workingDir = path.substring(0, path.lastIndexOf("/"));
    String file = path.substring(path.lastIndexOf("/") + 1);
    ftp.changeWorkingDirectory(workingDir);
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

    InputStream input = new FilterInputStream(ftp.retrieveFileStream(file)) {

        public void close() throws IOException {
            in.close();
            ftp.quit();
            ftp.disconnect();
        }
    };

    return input;
}

From source file:org.apache.activemq.blob.FTPBlobUploadStrategy.java

@Override
public URL uploadStream(ActiveMQBlobMessage message, InputStream in) throws JMSException, IOException {

    FTPClient ftp = createFTP();
    try {// ww w. j  a va  2 s .  co m
        String path = url.getPath();
        String workingDir = path.substring(0, path.lastIndexOf("/"));
        String filename = message.getMessageId().toString().replaceAll(":", "_");
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

        String url;
        if (!ftp.changeWorkingDirectory(workingDir)) {
            url = this.url.toString().replaceFirst(this.url.getPath(), "") + "/";
        } else {
            url = this.url.toString();
        }

        if (!ftp.storeFile(filename, in)) {
            throw new JMSException("FTP store failed: " + ftp.getReplyString());
        }
        return new URL(url + filename);
    } finally {
        ftp.quit();
        ftp.disconnect();
    }

}

From source file:org.apache.flume.source.FTPSource.java

@SuppressWarnings("UnnecessaryContinue")
public void discoverElements(FTPClient ftpClient, String parentDir, String currentDir, int level)
        throws IOException {

    String dirToList = parentDir;
    if (!currentDir.equals("")) {
        dirToList += "/" + currentDir;
    }/*from   www . ja v a 2  s . c  o m*/
    FTPFile[] subFiles = ftpClient.listFiles(dirToList);
    if (subFiles != null && subFiles.length > 0) {

        for (FTPFile aFile : subFiles) {
            String currentFileName = aFile.getName();
            if (currentFileName.equals(".") || currentFileName.equals("..")) {
                log.info("Skip parent directory and directory itself");
                continue;
            }

            if (aFile.isDirectory()) {
                log.info("[" + aFile.getName() + "]");
                ftpClient.changeWorkingDirectory(parentDir);
                discoverElements(ftpClient, dirToList, aFile.getName(), level + 1);
                continue;
            } else if (aFile.isFile()) { //aFile is a regular file
                ftpClient.changeWorkingDirectory(dirToList);
                existFileList.add(dirToList + "/" + aFile.getName()); //control of deleted files in server
                String fileName = aFile.getName();
                if (!(sizeFileList.containsKey(dirToList + "/" + aFile.getName()))) { //new file
                    ftpSourceCounter.incrementFilesCount();
                    InputStream inputStream = null;
                    try {
                        inputStream = ftpClient.retrieveFileStream(aFile.getName());
                        listener.fileStreamRetrieved();
                        readStream(inputStream, 0);
                        boolean success = inputStream != null && ftpClient.completePendingCommand(); //mandatory
                        if (success) {
                            sizeFileList.put(dirToList + "/" + aFile.getName(), aFile.getSize());
                            saveMap(sizeFileList);
                            ftpSourceCounter.incrementFilesProcCount();
                            log.info("discovered: " + fileName + " ," + sizeFileList.size());
                        } else {
                            handleProcessError(fileName);
                        }
                    } catch (FTPConnectionClosedException e) {
                        handleProcessError(fileName);
                        log.error("Ftp server closed connection ", e);
                        continue;
                    }

                    ftpClient.changeWorkingDirectory(dirToList);
                    continue;

                } else { //known file                        
                    long dif = aFile.getSize() - sizeFileList.get(dirToList + "/" + aFile.getName());
                    if (dif > 0) { //known and modified
                        long prevSize = sizeFileList.get(dirToList + "/" + aFile.getName());
                        InputStream inputStream = null;
                        try {
                            inputStream = ftpClient.retrieveFileStream(aFile.getName());
                            listener.fileStreamRetrieved();
                            readStream(inputStream, prevSize);

                            boolean success = inputStream != null && ftpClient.completePendingCommand(); //mandatory
                            if (success) {
                                sizeFileList.put(dirToList + "/" + aFile.getName(), aFile.getSize());
                                saveMap(sizeFileList);
                                ftpSourceCounter.incrementCountModProc();
                                log.info("modified: " + fileName + " ," + sizeFileList.size());
                            } else {
                                handleProcessError(fileName);
                            }
                        } catch (FTPConnectionClosedException e) {
                            log.error("Ftp server closed connection ", e);
                            handleProcessError(fileName);
                            continue;
                        }

                        ftpClient.changeWorkingDirectory(dirToList);
                        continue;
                    } else if (dif < 0) { //known and full modified
                        existFileList.remove(dirToList + "/" + aFile.getName()); //will be rediscovered as new file
                        saveMap(sizeFileList);
                        continue;
                    }
                    ftpClient.changeWorkingDirectory(parentDir);
                    continue;
                }
            } else if (aFile.isSymbolicLink()) {
                log.info(aFile.getName() + " is a link of " + aFile.getLink() + " access denied");
                ftpClient.changeWorkingDirectory(parentDir);
                continue;
            } else if (aFile.isUnknown()) {
                log.info(aFile.getName() + " unknown type of file");
                ftpClient.changeWorkingDirectory(parentDir);
                continue;
            } else {
                ftpClient.changeWorkingDirectory(parentDir);
                continue;
            }

        } //fin de bucle
    } //el listado no es vaco
}

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

@Override
public FSDataInputStream open(Path file, int bufferSize) throws IOException {
    FTPClient client = connect();
    Path workDir = new Path(client.printWorkingDirectory());
    Path absolute = makeAbsolute(workDir, file);
    FileStatus fileStat = getFileStatus(client, absolute);
    if (fileStat.isDir()) {
        disconnect(client);/*  ww  w  . j  a  v  a 2  s  .  c o  m*/
        throw new IOException("Path " + file + " is a directory.");
    }
    client.allocate(bufferSize);
    Path parent = absolute.getParent();
    // Change to parent directory on the
    // server. Only then can we read the
    // file
    // on the server by opening up an InputStream. As a side effect the working
    // directory on the server is changed to the parent directory of the file.
    // The FTP client connection is closed when close() is called on the
    // FSDataInputStream.
    client.changeWorkingDirectory(parent.toUri().getPath());
    InputStream is = client.retrieveFileStream(file.getName());
    FSDataInputStream fis = new FSDataInputStream(new FTPInputStream(is, client, statistics));
    if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
        // The ftpClient is an inconsistent state. Must close the stream
        // which in turn will logout and disconnect from FTP server
        fis.close();
        throw new IOException("Unable to open file: " + file + ", Aborting");
    }
    return fis;
}

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

/**
 * A stream obtained via this call must be closed before using other APIs of
 * this class or else the invocation will block.
 *///from www . ja v  a 2 s.co m
@Override
public FSDataOutputStream create(Path file, FsPermission permission, boolean overwrite, int bufferSize,
        short replication, long blockSize, Progressable progress) throws IOException {
    final FTPClient client = connect();
    Path workDir = new Path(client.printWorkingDirectory());
    Path absolute = makeAbsolute(workDir, file);
    if (exists(client, file)) {
        if (overwrite) {
            delete(client, file);
        } else {
            disconnect(client);
            throw new IOException("File already exists: " + file);
        }
    }
    Path parent = absolute.getParent();
    if (parent == null || !mkdirs(client, parent, FsPermission.getDefault())) {
        parent = (parent == null) ? new Path("/") : parent;
        disconnect(client);
        throw new IOException("create(): Mkdirs failed to create: " + parent);
    }
    client.allocate(bufferSize);
    // Change to parent directory on the server. Only then can we write to the
    // file on the server by opening up an OutputStream. As a side effect the
    // working directory on the server is changed to the parent directory of the
    // file. The FTP client connection is closed when close() is called on the
    // FSDataOutputStream.
    client.changeWorkingDirectory(parent.toUri().getPath());
    FSDataOutputStream fos = new FSDataOutputStream(client.storeFileStream(file.getName()), statistics) {
        @Override
        public void close() throws IOException {
            super.close();
            if (!client.isConnected()) {
                throw new FTPException("Client not connected");
            }
            boolean cmdCompleted = client.completePendingCommand();
            disconnect(client);
            if (!cmdCompleted) {
                throw new FTPException("Could not complete transfer, Reply Code - " + client.getReplyCode());
            }
        }
    };
    if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
        // The ftpClient is an inconsistent state. Must close the stream
        // which in turn will logout and disconnect from FTP server
        fos.close();
        throw new IOException("Unable to create file: " + file + ", Aborting");
    }
    return fos;
}

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.
 *//*ww  w .ja v a  2 s  . c o  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;
}