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

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

Introduction

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

Prototype

public boolean login(String username, String password) throws IOException 

Source Link

Document

Login to the FTP server using the provided username and password.

Usage

From source file:no.imr.sea2data.stox.InstallerUtil.java

public static boolean retrieveReferenceFromFTP() {
    FTPClient ftpClient = new FTPClient();
    try {//from w  w w.  j a  v a  2  s .  c om
        // pass directory path on server to connect  
        ftpClient.connect("ftp.imr.no");
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        // successful  
        if (!ftpClient.login("anonymous", "")) {
            return false;
        }
        ftpClient.enterLocalPassiveMode();
        FTPUtil.retrieveDir(ftpClient, FTP_STOXDOWNLOAD_REFERENCE, ProjectUtils.getSystemReferenceFolder());
    } catch (Exception e) {
        return false;
    } finally {
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
        }
    }
    return true;
}

From source file:nz.co.jsrsolutions.ds3.provider.CMEEodDataProvider.java

public CMEEodDataProvider(String hostname, String basePath, CMEEodDataProviderExchangeDescriptor[] descriptors)
        throws EodDataProviderException {

    _hostname = hostname;//from  w w  w.j a va  2  s.  c o  m
    _basePath = basePath;
    _descriptors = descriptors;

    FTPClient ftp = new FTPClient();
    FTPClientConfig config = new FTPClientConfig();
    ftp.configure(config);
    boolean error = false;
    try {
        int reply;
        ftp.connect(_hostname);
        _logger.info("Connected to " + _hostname);
        _logger.info(ftp.getReplyString());

        // After connection attempt, you should check the reply code to
        // verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            _logger.error("FTP server refused connection.");
            throw new EodDataProviderException("FTP server refused connection.");
        }

        boolean result = ftp.login("anonymous", "jsr@argusat.com");

        result = ftp.changeWorkingDirectory(_basePath);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            _logger.error(reply);
            throw new EodDataProviderException("Failed to cd into " + _basePath);
        }

        for (CMEEodDataProviderExchangeDescriptor descriptor : _descriptors) {

            OutputStream output = new ByteArrayOutputStream();

            String modificationTime = ftp.getModificationTime(descriptor.getFilename());

            // 213 20131202235804\r\n

            result = ftp.retrieveFile(descriptor.getFilename(), output);

            output.close();
        }

        ftp.logout();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
}

From source file:org.abstracthorizon.proximity.storage.remote.CommonsNetFtpRemotePeer.java

/**
 * Gets the FTP client./*from w w w.j a va  2 s . c  om*/
 * 
 * @return the FTP client
 */
public FTPClient getFTPClient() {
    try {
        logger.info("Creating CommonsNetFTPClient instance");
        FTPClient ftpc = new FTPClient();
        ftpc.configure(ftpClientConfig);
        ftpc.connect(getRemoteUrl().getHost());
        ftpc.login(getFtpUsername(), getFtpPassword());
        ftpc.setFileType(FTPClient.BINARY_FILE_TYPE);
        return ftpc;
    } catch (SocketException ex) {
        throw new StorageException("Got SocketException while creating FTPClient", ex);
    } catch (IOException ex) {
        throw new StorageException("Got IOException while creating FTPClient", ex);
    }
}

From source file:org.alfresco.bm.file.FtpTestFileService.java

/**
 * Provides a safe (connected) FTP client
 *///from  w ww  . jav  a  2 s . c om
private FTPClient getFTPClient() throws IOException {
    // Connect to the FTP server
    FTPClient ftp = new FTPClient();

    // Connect and login 
    ftp.connect(ftpHost, ftpPort);
    if (!ftp.login(ftpUsername, ftpPassword)) {
        throw new IOException("FTP credentials rejected.");
    }

    if (ftpLocalPassiveMode) {
        ftp.enterLocalPassiveMode();
    }

    // Settings for the FTP channel
    ftp.setControlKeepAliveTimeout(300);
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    ftp.setAutodetectUTF8(false);
    int reply = ftp.getReplyCode();

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

    // Done
    return ftp;
}

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

/**
 * Simple test that connects to the inbuilt ftp server and logs on
 * /*from   w w  w .ja  v  a2 s  . co m*/
 * @throws Exception
 */
public void testFTPConnect() throws Exception {
    logger.debug("Start testFTPConnect");

    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 not successful", login);
    } finally {
        ftp.disconnect();
    }
}

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

/**
 * Simple negative test that connects to the inbuilt ftp server and attempts to 
 * log on with the wrong password.//  w ww . ja  va  2s. co  m
 * 
 * @throws Exception
 */
public void testFTPConnectNegative() throws Exception {
    logger.debug("Start testFTPConnectNegative");

    FTPClient ftp = connectClient();

    try {
        int reply = ftp.getReplyCode();

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

        boolean login = ftp.login(USER_ADMIN, "garbage");
        assertFalse("admin login successful", login);

        // now attempt to list the files and check that the command does not 
        // succeed
        FTPFile[] files = ftp.listFiles();

        assertNotNull(files);
        assertTrue(files.length == 0);
        reply = ftp.getReplyCode();

        assertTrue(FTPReply.isNegativePermanent(reply));

    } finally {
        ftp.disconnect();
    }
}

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

/**
 * Test CWD for FTP server/*from w  ww . jav  a  2  s  .  c  om*/
 * 
 * @throws Exception
 */
public void testCWD() throws Exception {
    logger.debug("Start testCWD");

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

        FTPFile[] files = ftp.listFiles();
        reply = ftp.getReplyCode();
        assertTrue(FTPReply.isPositiveCompletion(reply));

        assertTrue(files.length == 1);

        boolean foundAlfresco = false;
        for (FTPFile file : files) {
            logger.debug("file name=" + file.getName());
            assertTrue(file.isDirectory());

            if (file.getName().equalsIgnoreCase("Alfresco")) {
                foundAlfresco = true;
            }
        }
        assertTrue(foundAlfresco);

        // Change to Alfresco Dir that we know exists
        reply = ftp.cwd("/Alfresco");
        assertTrue(FTPReply.isPositiveCompletion(reply));

        // relative path with space char
        reply = ftp.cwd("Data Dictionary");
        assertTrue(FTPReply.isPositiveCompletion(reply));

        // non existant absolute
        reply = ftp.cwd("/Garbage");
        assertTrue(FTPReply.isNegativePermanent(reply));

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

        // Wild card
        reply = ftp.cwd("/Alfresco/User*Homes");
        assertTrue("unable to change to /Alfresco User*Homes/", FTPReply.isPositiveCompletion(reply));

        //            // Single char pattern match
        //            reply = ftp.cwd("/Alfre?co");
        //            assertTrue("Unable to match single char /Alfre?co", FTPReply.isPositiveCompletion(reply));

        // two level folder
        reply = ftp.cwd("/Alfresco/Data Dictionary");
        assertTrue("unable to change to /Alfresco/Data Dictionary", FTPReply.isPositiveCompletion(reply));

        // go up one
        reply = ftp.cwd("..");
        assertTrue("unable to change to ..", FTPReply.isPositiveCompletion(reply));

        reply = ftp.pwd();
        ftp.getStatus();

        assertTrue("unable to get status", FTPReply.isPositiveCompletion(reply));

        // check we are at the correct point in the tree
        reply = ftp.cwd("Data Dictionary");
        assertTrue(FTPReply.isPositiveCompletion(reply));

    } finally {
        ftp.disconnect();
    }

}

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

/**
 * Test CRUD for FTP server//from  ww w  .j  ava2s.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
 * /*w  w  w  .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/*from w  w w.j  a  va  2s .  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();
    }

}