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:org.schedoscope.export.ftp.FtpExportCSVMRTest.java

private int getFileCount() throws IOException {

    FTPClient ftp = new FTPClient();
    ftp.connect("localhost", 2221);
    ftp.login(EmbeddedFtpSftpServer.FTP_USER_FOR_TESTING, EmbeddedFtpSftpServer.FTP_PASS_FOR_TESTING);
    FTPFile[] files = ftp.listFiles();/*from   w  ww  .jav  a2 s .  c o  m*/

    int fileCounter = 0;
    for (FTPFile f : files) {
        if (f.getName().contains(filePrefix)) {
            fileCounter += 1;
        }
    }
    return fileCounter;
}

From source file:org.shept.util.FtpFileCopy.java

/**
 * @param//from w  w w  . j av  a  2  s. c om
 * @return
 *
 * @param config
 * @param ftpC
 * @throws SocketException
 * @throws IOException
 */
private boolean configSetup(FtpConfig config, FTPClient ftpC) throws IOException {
    boolean rc;
    ftpC.connect(config.getHostAddress(), config.getPort());
    rc = ftpC.login(config.getUserName(), config.getPassword());
    if (!rc) {
        logger.error("Ftp could not log to remote server with " + config.getUserName());
        return false;
    }
    if (StringUtils.hasText(config.getServerPath())) {
        int cwdCode = ftpC.cwd(config.getServerPath());
        if (!FTPReply.isPositiveCompletion(cwdCode)) {
            logger.error("Ftp could not change working dir to " + config.getServerPath()
                    + " - Server returned Code " + cwdCode);
            return false;
        }
    }
    rc = ftpC.setFileType(config.getFileType());
    if (!rc) {
        logger.error("Ftp could not change FileType for transmission");
        return false;
    }
    return true;
}

From source file:org.sipfoundry.preflight.FTP.java

public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService,
        InetAddress bindAddress) {
    ResultCode results = NONE;/*from www  .ja  v a  2 s .  c om*/
    InetAddress ftpServerAddress = null;
    String testFile = new String("00D01EFFFFFE");
    String[] verificationStrings = { "LIP-68XX configuration information", "[VOIP]", "outbound_proxy_server",
            "[PROVISION]", "decrypt_key" };

    if (networkResources.configServer == null) {
        journalService.println("No FTP server provided, skipping test.\n");
        return CONFIG_SERVER_MISSING;
    }

    journalService.println("Starting FTP server test.");

    if (IPAddressUtil.isLiteralIPAddress(networkResources.configServer)) {
        try {
            ftpServerAddress = InetAddress.getByName(networkResources.configServer);
        } catch (UnknownHostException e) {
            // Should never get here.
            e.printStackTrace();
        }
        journalService.println("Using FTP server literal address: " + networkResources.configServer);
    } else {
        // Try to retrieve A RECORD for FTP server, checking each DNS server.
        SimpleResolver resolver = null;
        try {
            resolver = new SimpleResolver();
            resolver.setLocalAddress(bindAddress);
            resolver.setTimeout(timeout);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        for (InetAddress dnsServer : networkResources.domainNameServers) {
            journalService.println(
                    "Looking up FTP server address via DNS server: " + dnsServer.getCanonicalHostName());
            String targetMessage = new String("  FTP server address \"" + networkResources.configServer + "\"");
            resolver.setAddress(dnsServer);
            Lookup aLookup = null;
            try {
                aLookup = new Lookup(networkResources.configServer, Type.A);
            } catch (TextParseException e) {
                journalService.println("  is malformed.\n");
                journalService.println(targetMessage);
                return FTP_ADDRESS_MALFORMED;
            }
            aLookup.setResolver(resolver);
            Record[] aRecords = aLookup.run();
            switch (aLookup.getResult()) {
            case Lookup.SUCCESSFUL:
                if (aRecords != null) {
                    InetAddress targetAddress = ((ARecord) aRecords[0]).getAddress();
                    targetMessage += " resolves to: " + targetAddress.getHostAddress();
                    journalService.println(targetMessage);
                    if (ftpServerAddress == null) {
                        ftpServerAddress = targetAddress;
                    } else {
                        // Check that multiple lookups result in same
                        // address.
                        if (!ftpServerAddress.equals(targetAddress)) {
                            journalService.println("  FTP server address does not match prior lookup.");
                            results = MULTIPLE_CONFIG_TARGETS;
                        }
                    }
                } else {
                    targetMessage += " could not be resolved.";
                    journalService.println(targetMessage);
                    results = FTP_TARGET_UNRESOLVED;
                }
                break;
            case Lookup.UNRECOVERABLE:
                targetMessage += " [Unrecoverable error]";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TRY_AGAIN:
                targetMessage += " [Lookup timeout]";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.HOST_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TYPE_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            }
        }
    }

    if ((ftpServerAddress == null) || (results == MULTIPLE_CONFIG_TARGETS)) {
        journalService.println("Cannot recover from previous errors, aborting FTP test.\n");
        return results;
    }

    journalService.println("Beginning FTP get request of test file: " + testFile);

    // Open the FTP connection.
    FTPClient ftp = new FTPClient();
    ftp.setDefaultTimeout(timeout * 1000);
    ftp.addProtocolCommandListener(new PrintCommandListener(journalService));

    try {
        int reply;
        ftp.connect(ftpServerAddress, 21, bindAddress, bindPort);

        // After connection, check reply code to verify.
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            journalService.println("FTP client failure: " + reply + "\n");
            return FTP_CLIENT_FAILURE;
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // Ignore.
            }
        }
        journalService.println("FTP client failure: " + e.getMessage() + "\n");
        return FTP_CLIENT_FAILURE;
    }

    try {
        if (!ftp.login(ftpUser, ftpPassword)) {
            ftp.logout();
            journalService.println("FTP client unable to log in.\n");
            return FTP_GET_FAILED;
        }

        journalService.println("FTP client connected to: " + ftp.getSystemName());

        ftp.enterLocalPassiveMode();

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ftp.retrieveFile(testFile, output);

        // After receiving, check reply code to verify.
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            journalService.println("FTP get failure: " + reply + "\n");
            return FTP_GET_FAILED;
        }

        ftp.logout();

        String testFileContents = output.toString();
        boolean verified = true;
        for (String verificationString : verificationStrings) {
            if (!testFileContents.contains(verificationString)) {
                verified = false;
            }
        }
        if (verified) {
            journalService.println("File received successfully.");
        } else {
            journalService.println("File received but contents do not verify.");
            System.err.println(testFileContents);
            results = FTP_CONTENTS_FAILED;
        }
    } catch (FTPConnectionClosedException e) {
        journalService.println("FTP server closed connection prematurely.\n");
        return FTP_GET_FAILED;
    } catch (IOException e) {
        journalService.println("FTP client failure. " + e.getMessage() + "\n");
        return FTP_CLIENT_FAILURE;
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // Ignore.
            }
        }
    }

    journalService.println("");
    return results;
}

From source file:org.spongepowered.repoindexer.FTPUtils.java

public static boolean uploadFTP(String user, String pass, String server, File local, String remoteLocation) {
    FTPClient ftpClient = new FTPClient();
    boolean done = false;
    try {/* w  ww . ja v a  2 s .  c o  m*/

        ftpClient.connect(server);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        InputStream inputStream = new FileInputStream(local);
        done = ftpClient.storeFile(remoteLocation, inputStream);
        inputStream.close();
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
        return false;
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return done;
    }
}

From source file:org.structr.files.ftp.FtpAccessTest.java

public void test01LoginFailed() {

    try (final Tx tx = StructrApp.getInstance(securityContext).tx()) {

        FTPClient ftp = new FTPClient();

        ftp.connect("127.0.0.1", ftpPort);
        logger.log(Level.INFO, "Reply from FTP server:", ftp.getReplyString());

        int reply = ftp.getReplyCode();
        assertTrue(FTPReply.isPositiveCompletion(reply));

        boolean loginSuccess = ftp.login("jt978hasdl", "lj3498ha");
        logger.log(Level.INFO, "Try to login as jt978hasdl/lj3498ha:", loginSuccess);
        assertFalse(loginSuccess);//from   w  w  w  .  jav a  2  s  . c  om

        ftp.disconnect();

    } catch (IOException | FrameworkException ex) {
        logger.log(Level.SEVERE, "Error in FTP test", ex);
        fail("Unexpected exception: " + ex.getMessage());
    }

}

From source file:org.structr.web.common.FtpTest.java

/**
 * Creates an FTP client, a backend user and logs this user in.
 *
 * @return/*from  w  w w .j  a  v  a  2 s  . c om*/
 */
protected FTPClient setupFTPClient() {

    FTPClient ftp = new FTPClient();

    try {

        ftp.connect("localhost", ftpPort);
        logger.log(Level.INFO, "Reply from FTP server:", ftp.getReplyString());

        int reply = ftp.getReplyCode();
        assertTrue(FTPReply.isPositiveCompletion(reply));

        String username = "ftpuser1";
        String password = "ftpuserpw1";

        try (final Tx tx = StructrApp.getInstance(securityContext).tx()) {
            ftpUser = createFTPUser(username, password);
            tx.success();
        } catch (FrameworkException fex) {
            logger.log(Level.SEVERE, "Unable to create FTP user", fex);
        }
        boolean loginSuccess = ftp.login(username, password);
        logger.log(Level.INFO, "Try to login as " + username + "/" + password + ": ", loginSuccess);
        assertTrue(loginSuccess);

        reply = ftp.getReplyCode();
        assertEquals(FTPReply.USER_LOGGED_IN, reply);

    } catch (IOException ex) {
        logger.log(Level.SEVERE, "Error in FTP test", ex);
        fail("Unexpected exception: " + ex.getMessage());
    }

    return ftp;

}

From source file:org.structr.web.files.FtpTest.java

/**
 * Creates an FTP client, a backend user and logs this user in.
 *
 * @param username// w w w .  ja v  a2s.  c o  m
 * @return
 */
protected FTPClient setupFTPClient(final String username) {

    FTPClient ftp = new FTPClient();

    try {

        ftp.connect("localhost", ftpPort);
        logger.info("Reply from FTP server:", ftp.getReplyString());

        int reply = ftp.getReplyCode();
        assertTrue(FTPReply.isPositiveCompletion(reply));

        String password = "ftpuserpw1";

        try (final Tx tx = StructrApp.getInstance(securityContext).tx()) {
            ftpUser = createFTPUser(username, password);
            tx.success();
        } catch (FrameworkException fex) {
            logger.error("Unable to create FTP user", fex);
        }

        boolean loginSuccess = ftp.login(username, password);
        logger.info("Tried to login as {}/{}: {}", new Object[] { username, password, loginSuccess });
        assertTrue(loginSuccess);

        reply = ftp.getReplyCode();
        assertEquals(FTPReply.USER_LOGGED_IN, reply);

    } catch (IOException ex) {
        logger.error("Error in FTP test", ex);
        fail("Unexpected exception: " + ex.getMessage());
    }

    return ftp;

}

From source file:org.syncany.tests.connection.plugins.ftp.EmbeddedTestFtpServer.java

public static void mkdir(String path, String user) throws SocketException, IOException {
    FTPClient ftp = new FTPClient();
    ftp.setConnectTimeout(3000);//  ww  w  .  java  2s .  co  m
    ftp.setDataTimeout(3000);
    ftp.setDefaultTimeout(3000);

    ftp.connect(HOST, PORT);
    ftp.login(user, PASSWORD1);
    ftp.enterLocalPassiveMode();
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // Important !!!
    ftp.makeDirectory(path);

    ftp.disconnect();
    ftp = null;
}

From source file:org.syncany.tests.plugins.ftp.EmbeddedTestFtpServer.java

public static void createTestFile(String path, String user) throws SocketException, IOException {
    FTPClient ftp = new FTPClient();
    ftp.setConnectTimeout(3000);/*from ww w. j a  va2s .  com*/
    ftp.setDataTimeout(3000);
    ftp.setDefaultTimeout(3000);

    ftp.connect(HOST, PORT);
    ftp.login(user, PASSWORD1);
    ftp.enterLocalPassiveMode();
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // Important !!!
    ftp.storeFile(path, new ByteArrayInputStream(new byte[] { 0x01, 0x02 }));

    ftp.disconnect();
    ftp = null;
}

From source file:org.teiid.resource.adapter.ftp.FtpManagedConnectionFactory.java

protected FTPClient createClient() throws IOException, ResourceException {

    FTPClient client = createClientInstance();

    beforeConnectProcessing(client);// w  ww.  jav  a2s. co m

    client.connect(this.host, this.port);

    if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
        throw new ResourceException(UTIL.getString("ftp_connect_failed", this.host, this.port)); //$NON-NLS-1$
    }

    if (!client.login(this.username, this.password)) {
        throw new IllegalStateException(UTIL.getString("ftp_login_failed", client.getReplyString())); //$NON-NLS-1$
    }

    afterConnectProcessing(client);

    return client;

}