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

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

Introduction

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

Prototype

public void enterLocalPassiveMode() 

Source Link

Document

Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE .

Usage

From source file:org.ramadda.repository.type.FtpTypeHandler.java

/**
 * _more_/* w ww.j av  a 2  s.  c o m*/
 *
 * @param server _more_
 * @param baseDir _more_
 * @param user _more_
 * @param password _more_
 *
 * @return _more_
 *
 * @throws Exception _more_
 */
public static String test(String server, String baseDir, String user, String password) throws Exception {
    FTPClient ftpClient = new FTPClient();
    try {
        String file = baseDir;
        ftpClient.connect(server);
        //System.out.print(ftp.getReplyString());
        ftpClient.login(user, password);
        //            System.out.print(ftpClient.getReplyString());
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            System.err.println("FTP server refused connection.");

            return null;
        }
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();

        boolean isDir = isDir(ftpClient, file);
        //            System.err.println("file:" + file + " is dir: " + isDir);

        if (isDir) {
            FTPFile[] files = ftpClient.listFiles(file);
            for (int i = 0; i < files.length; i++) {
                //                    System.err.println ("f:" + files[i].getName() + " " + files[i].isDirectory() + "  " + files[i].isFile());
            }
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            if (ftpClient.retrieveFile(file, bos)) {
                //                    System.err.println(new String(bos.toByteArray()));
            } else {
                throw new IOException("Unable to retrieve file:" + file);
            }
        }

        return "";
    } finally {
        closeConnection(ftpClient);
    }
}

From source file:org.ramadda.repository.type.FtpTypeHandler.java

/**
 * _more_//w  ww .j  a  v  a 2  s .c om
 *
 * @param parentEntry _more_
 *
 * @return _more_
 *
 * @throws Exception _more_
 */
private FTPClient getFtpClient(Entry parentEntry) throws Exception {
    Object[] values = parentEntry.getValues();
    if (values == null) {
        return null;
    }
    String server = (String) values[COL_SERVER];
    String baseDir = (String) values[COL_BASEDIR];
    String user = (String) values[COL_USER];
    String password = (String) values[COL_PASSWORD];
    if (password != null) {
        password = getRepository().getPageHandler().processTemplate(password, false);
    } else {
        password = "";
    }
    FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect(server);
        if (user != null) {
            ftpClient.login(user, password);
        }
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            System.err.println("FTP server refused connection.");

            return null;
        }
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();

        return ftpClient;
    } catch (Exception exc) {
        System.err.println("Could not connect to ftp server:" + server + "\nError:" + exc);

        return null;
    }
}

From source file:org.ramadda.util.Utils.java

/**
 * _more_/* ww  w . j a  v  a2 s .  c om*/
 *
 * @param url _more_
 *
 * @return _more_
 *
 * @throws Exception _more_
 */
public static FTPClient makeFTPClient(URL url) throws Exception {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(url.getHost());
    ftpClient.login("anonymous", "");
    int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
        System.err.println("FTP server refused connection.");

        return null;
    }
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    ftpClient.enterLocalPassiveMode();

    return ftpClient;
}

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

public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService,
        InetAddress bindAddress) {
    ResultCode results = NONE;/* w w  w .j  ava  2s  .c  o m*/
    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  w w.  j a v a2s  .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.springframework.integration.ftp.session.AbstractFtpSessionFactory.java

/**
 * Sets the mode of the connection. Only local modes are supported.
 *//*from w ww  .j  ava2  s . co m*/
private void updateClientMode(FTPClient client) {
    switch (this.clientMode) {
    case FTPClient.ACTIVE_LOCAL_DATA_CONNECTION_MODE:
        client.enterLocalActiveMode();
        break;
    case FTPClient.PASSIVE_LOCAL_DATA_CONNECTION_MODE:
        client.enterLocalPassiveMode();
        break;
    default:
        break;
    }
}

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);//from  ww  w.j a  v  a2  s  .c o 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  w ww  . j  a va2s  .  c o  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.storeFile(path, new ByteArrayInputStream(new byte[] { 0x01, 0x02 }));

    ftp.disconnect();
    ftp = null;
}

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

private void updateClientMode(FTPClient client) {
    switch (this.clientMode) {
    case ACTIVE_LOCAL_DATA_CONNECTION_MODE:
        client.enterLocalActiveMode();/* w w  w  .  ja  v a 2  s.  c o  m*/
        break;
    case PASSIVE_LOCAL_DATA_CONNECTION_MODE:
        client.enterLocalPassiveMode();
        break;
    default:
        break;
    }
}

From source file:org.umit.icm.mobile.connectivity.ServiceFTP.java

/**
 * Returns an FTP Response String./*  w ww . j a va  2s  .  c  om*/
 * 
 *                                                                                                 
              
@return      String
 *
         
@see FTPClient
 */
@Override
public String connect() {

    FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect(getServiceURL());
        ftpClient.login("test", "test");
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        String reply = ftpClient.getReplyString();
        ftpClient.logout();
        ftpClient.disconnect();
        if (reply != null)
            return "normal";
        return "blocked";
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}