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

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

Introduction

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

Prototype

public FTPClient() 

Source Link

Document

Default FTPClient constructor.

Usage

From source file:au.org.intersect.dms.wn.transports.impl.FtpConnection.java

public FtpConnection(String server, String username, String password) {
    LOGGER.debug("ftp connect to server:{} using username:{} and password:{}",
            new String[] { server, username, password });
    boolean ok = false;
    params = new ConnectionParams("ftp", server, username, null);
    try {//w w  w  .  ja va  2 s.  c  o m
        client = new FTPClient();
        client.connect(server);
        client.enterLocalPassiveMode();
        if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
            throw new TransportError();
        }
        if (!client.login(username, password)) {
            throw new NotAuthorizedError();
        }
        client.setFileType(FTP.BINARY_FILE_TYPE);
        ok = true;
    } catch (SocketException e) {
        throw new TransportError(e);
    } catch (IOException e) {
        throw new TransportError(e);
    } finally {
        if (!ok && client != null) {
            try {
                client.disconnect();
            } catch (IOException e) {
                // swallows exception
            }
        }
    }
}

From source file:com.seajas.search.contender.service.modifier.AbstractModifierService.java

/**
 * Retrieve the FTP client belonging to the given URI.
 * /*from  w w w . ja  v  a2s  .  c o  m*/
 * @param uri
 * @return FTPClient
 */
protected FTPClient retrieveFtpClient(final URI uri) {
    // Create the FTP client

    FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient();

    try {
        ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21);

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not connect to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        if (StringUtils.hasText(uri.getUserInfo())) {
            if (uri.getUserInfo().contains(":"))
                ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")),
                        uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1));
            else
                ftpClient.login(uri.getUserInfo(), "");
        }

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not login to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        // Switch to PASV and BINARY mode

        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        return ftpClient;
    } catch (IOException e) {
        logger.error("Could not close input stream during archive processing", e);
    }

    return null;
}

From source file:mysynopsis.FTPUploader.java

public static String uploadWizard() throws IOException {

    FTPClient connect;/*from  w w w . j  a  v a2 s . c o  m*/
    connect = null;

    try {
        connect = new FTPClient();
        connect.connect(server, 21);
        int reply = connect.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            connect.disconnect();
            return "Can't Connect to the Server";
        }

        boolean check = connect.login(user, pass);
        if (!check) {
            return "Username or password Incorrect";
        }

        connect.setFileType(FTP.BINARY_FILE_TYPE);
        connect.enterLocalPassiveMode();

        InputStream input;
        try {
            input = new FileInputStream(new File("index.html"));
            connect.storeFile(dir + "index.html", input);
            input.close();
            connect.logout();
            connect.disconnect();

        } catch (IOException ex) {
            return "You need to put a slash (/) at the end";
        }
    } catch (IOException iOException) {
        return "Wrong Server Information. Please Try again";
    }
    return "File Transfer Successful!";
}

From source file:cycronix.ctlib.CTftp.java

/**
 * FTP login with secure (FTPS) connection
 * @param host host name//from  www  .j a va  2s .  c  o m
 * @param user user name
 * @param pw password
 * @param secure T/F
 * @throws Exception on error
 */
public void login(String host, String user, String pw, boolean secure) throws Exception {
    if (secure)
        client = new FTPSClient(true);
    else
        client = new FTPClient();

    client.connect(host);
    boolean success = client.login(user, pw);
    if (!success) {
        throw new IOException("FTP login failed, host: " + host + ", user: " + user);
    }
    client.setFileType(FTPClient.BINARY_FILE_TYPE);

    loginDir = client.printWorkingDirectory();
    CTinfo.debugPrint("FTP login, u: " + user + ", pw: " + pw + ", loginDir: " + loginDir);
}

From source file:com.recomdata.transmart.data.export.util.FTPUtil.java

/**
 * This method connects to the specified FTP Server:Port details in the
 * configuration file/* ww w.  ja va  2 s.  c o m*/
 * 
 * @throws InvalidFTPParamsException
 */
private static void connect() throws InvalidFTPParamsException {
    validate();
    ftp = new FTPClient();
    try {
        int reply;
        if (NumberUtils.isNumber(FTP_SERVER_PORT) && Integer.parseInt(FTP_SERVER_PORT) > 0) {
            ftp.connect(FTP_SERVER, Integer.parseInt(FTP_SERVER_PORT));
        } else {
            ftp.connect(FTP_SERVER);
        }
        System.out.println("Connected to " + FTP_SERVER + " on " + ftp.getRemotePort());

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                log.error(e.getMessage(), e);
            }
        }
        System.err.println("Could not connect to FTP server.");
        e.printStackTrace();
    }
}

From source file:ftp_server.FileUpload.java

public void uploadingWithProgress() {
    FTPClient ftp = new FTPClient();
    FileInputStream fis = null;/* www  . j a v a2  s. co  m*/
    try {
        ftp.connect("shamalmahesh.net78.net");
        ftp.login("a9959679", "9P3IckDo");
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.changeWorkingDirectory("/public_html/testing");
        int reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Uploading....");
        } else {
            System.out.println("Failed connect to the server!");
        }
        File f1 = new File("D:\\jpg\\1.jpg");

        //            fis = new FileInputStream(ftp.storeFile("one.jpg", fis));
        System.out.println("Done!");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.mitre.holdshort.AlertLogger.java

public AlertLogger(String airport, Context ctx) {

    this.ctx = ctx;
    this.airport = airport;
    try {/*from w  w w  . j a v  a  2 s.c  o m*/

        alertFTPClient = new FTPClient();
        alertFTPClient.connect(ftpHost, 21);
        alertFTPClient.login(ftpUser, ftpPassword);
        alertFTPClient.enterLocalPassiveMode();

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnknownHostException e) {
        System.err.println("No Connection For FTP Client");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Check for or create old alert file for when FTPClient cannot connect
    File oldAlerts = new File(ctx.getFilesDir() + "/oldAlerts.dat");
    if (!(oldAlerts.exists())) {
        try {
            oldAlerts.createNewFile();
        } catch (IOException e1) {

        }
    } else {
        //Old Alert file exists & push old alerts to the ftp server
        logOldAlerts();
    }

}

From source file:br.gov.frameworkdemoiselle.behave.regression.repository.FTPRepository.java

public FTPRepository() {
    super();
    tmpFolder = System.getProperty("java.io.tmpdir") + BAR + folder;
    ftp = new FTPClient();
}

From source file:com.naryx.tagfusion.cfm.tag.net.ftp.cfFTPData.java

public cfFTPData(String _Server, int _Port, String _Username, String _Password) {

    setPrivateData("server", new cfStringData(_Server));
    setPrivateData("port", new cfNumberData(_Port));

    this.username = _Username;
    this.password = _Password;

    ftpclient = new FTPClient();
}

From source file:ServeurFTP.java

public ServeurFTP(String server10, String username10, String password10, String file10, String server20,
        String username20, String password20, String file20) {
    String server1, username1, password1, file1;
    String server2, username2, password2, file2;
    String[] parts;// w ww .  j  a va2  s .co m
    int port1 = 0, port2 = 0;
    FTPClient ftp1, ftp2;
    ProtocolCommandListener listener;

    server1 = server10;
    parts = server1.split(":");
    if (parts.length == 2) {
        server1 = parts[0];
        port1 = Integer.parseInt(parts[1]);
    }
    username1 = username10;
    password1 = password10;
    file1 = file10;
    server2 = server20;
    parts = server2.split(":");
    if (parts.length == 2) {
        server2 = parts[0];
        port2 = Integer.parseInt(parts[1]);
    }
    username2 = username20;
    password2 = password20;
    file2 = file20;

    listener = new PrintCommandListener(new PrintWriter(System.out), true);
    ftp1 = new FTPClient();
    ftp1.addProtocolCommandListener(listener);
    ftp2 = new FTPClient();
    ftp2.addProtocolCommandListener(listener);

    try {
        int reply;
        if (port1 > 0) {
            ftp1.connect(server1, port1);
        } else {
            ftp1.connect(server1);
        }
        System.out.println("Connected to " + server1 + ".");

        reply = ftp1.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp1.disconnect();
            System.err.println("FTP server1 refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp1.isConnected()) {
            try {
                ftp1.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server1.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        int reply;
        if (port2 > 0) {
            ftp2.connect(server2, port2);
        } else {
            ftp2.connect(server2);
        }
        System.out.println("Connected to " + server2 + ".");

        reply = ftp2.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp2.disconnect();
            System.err.println("FTP server2 refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp2.isConnected()) {
            try {
                ftp2.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server2.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp1.login(username1, password1)) {
            System.err.println("Could not login to " + server1);
            break __main;
        }

        if (!ftp2.login(username2, password2)) {
            System.err.println("Could not login to " + server2);
            break __main;
        }

        // Let's just assume success for now.
        ftp2.enterRemotePassiveMode();

        ftp1.enterRemoteActiveMode(InetAddress.getByName(ftp2.getPassiveHost()), ftp2.getPassivePort());

        // Although you would think the store command should be sent to server2
        // first, in reality, ftp servers like wu-ftpd start accepting data
        // connections right after entering passive mode.  Additionally, they
        // don't even send the positive preliminary reply until after the
        // transfer is completed (in the case of passive mode transfers).
        // Therefore, calling store first would hang waiting for a preliminary
        // reply.
        if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2)) {
            //      if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) {
            // We have to fetch the positive completion reply.
            ftp1.completePendingCommand();
            ftp2.completePendingCommand();
        } else {
            System.err.println("Couldn't initiate transfer.  Check that filenames are valid.");
            break __main;
        }

    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        try {
            if (ftp1.isConnected()) {
                ftp1.logout();
                ftp1.disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }

        try {
            if (ftp2.isConnected()) {
                ftp2.logout();
                ftp2.disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }
    }
}