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:cn.zhuqi.mavenssh.web.util.test.FtpTest.java

/**
 *
 * @param path ftp?/*from   ww  w.j a  va2 s.c  om*/
 * @param addr ?
 * @param port ??
 * @param username ??
 * @param password ?
 * @return
 * @throws Exception
 */
private boolean connect(String path, String addr, int port, String username, String password) throws Exception {
    boolean result = false;
    ftpClient = new FTPClient();
    int reply;
    ftpClient.connect(addr, port);
    ftpClient.login(username, password);
    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
    reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
        return result;
    }
    ftpClient.changeWorkingDirectory(path);
    result = true;
    return result;
}

From source file:guru.nidi.ftpsync.fs.FtpFileSystem.java

public FtpFileSystem(String basedir, Config config) throws IOException {
    super(basedir);
    client = new FTPClient();
    client.connect(config.getHost());//from   w w w  .ja v a 2  s. c  om
    int reply = client.getReplyCode();

    if (!FTPReply.isPositiveCompletion(reply)) {
        client.disconnect();
        throw new IOException("FTP server refused connection.");
    }
    final boolean login = client.login(config.getUsername(), config.getPassword());
    if (!login) {
        throw new FtpException("Could not login", client.getReplyStrings());
    }
    client.setFileType(FTP.BINARY_FILE_TYPE);
}

From source file:Cursling.getFtpDetails.java

public String getFtpMonitorDetails(String url, String text_check) throws IOException {

    try {/* www . j  ava 2s  .co  m*/
        try {
            ftpClient.logout();
            ftpClient.disconnect();
        } catch (Exception e) {
            //ignore line
        }
        ftpClient = new FTPClient();
        // ftpClient.setSoTimeout(10);
        ftpClient.setConnectTimeout(global_ftp_timeout * 1000);
        String ftp_host = "";
        int ftp_port = 0000;
        String ftp_user = "";
        String ftp_pass = "";
        String isTextPresenset = "No";

        //Parsing ftp url
        String[] details = obj_parseftpurl.getParseFTPUrl(url);
        ftp_host = details[0];
        ftp_port = Integer.parseInt(details[1]);
        ftp_user = details[2];
        ftp_pass = details[3];

        if (!ftp_host.equalsIgnoreCase("") && ftp_port != 0000) {
            ftpClient.connect(ftp_host, ftp_port);
        }

        if (!ftp_host.equalsIgnoreCase("") && ftp_port == 0000) {
            ftpClient.connect(ftp_host);
        }
        if (ftpClient.isConnected()) {
            status = "Up";
            state = "alive";
        } else {
            status = "Down";
            state = "dead";
        }
        if (!ftp_user.equalsIgnoreCase("") && !ftp_pass.equalsIgnoreCase("")) {
            ftpClient.login(ftp_user, ftp_pass);
            int reply = ftpClient.getReplyCode();

            if (FTPReply.isPositiveCompletion(reply)) {
                status = "Up";
                state = "alive";
                if (text_check.equalsIgnoreCase("---")) { //do nothing
                    isTextPresenset = "---";
                } else {
                    FTPFile[] files = ftpClient.listFiles(text_check);
                    if (files.length == 1) {
                        isTextPresenset = "Yes";
                    } else if (files.length == 0) {
                        isTextPresenset = "No";
                    }
                }
            } else {
                status = "Auth Failed";
                isTextPresenset = "No";
                state = "dead";
            }

        } else {
            isTextPresenset = "---";
        }

        ftpClient.logout();
        ftpClient.disconnect();
        return ("\"" + url + "\",\"" + status + "\",\"" + "---" + "\",\"" + isTextPresenset + "\",\"" + state
                + "\"");

    } catch (Exception e) {

        if (e.toString().matches(".*java.net.ConnectException.*")) {
            logger.error("Error : java.net.ConnectException - " + url);
            status = "ConnectException";
        } else if (e.toString().matches(".*java.net.UnknownHostException.*")) {
            logger.error("Error : java.net.UnknownHostException - " + url);
            status = "UnknownHost";
        } else if (e.toString().matches(".*Timed.*out.*")) {
            logger.error("Error : " + e + " --- " + url);
            status = "TimeOut";
        } else {
            logger.error("Error - " + e + " --- " + url);
            status = "Failed";
        }

        return ("\"" + url + "\",\"" + status + "\",\"" + "---" + "\",\"" + "---" + "\",\"" + "dead" + "\"");

    }
}

From source file:ca.rmen.android.networkmonitor.app.speedtest.SpeedTestUpload.java

public static SpeedTestResult upload(SpeedTestUploadConfig uploadConfig) {
    Log.v(TAG, "upload " + uploadConfig);
    // Make sure we have a file to upload
    if (!uploadConfig.file.exists())
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);

    FTPClient ftp = new FTPClient();
    // For debugging, we'll log all the ftp commands
    if (BuildConfig.DEBUG) {
        PrintCommandListener printCommandListener = new PrintCommandListener(System.out);
        ftp.addProtocolCommandListener(printCommandListener);
    }/*  w  ww  .j av  a 2 s  . c o m*/
    InputStream is = null;
    try {
        // Set buffer size of FTP client
        ftp.setBufferSize(1048576);
        // Open a connection to the FTP server
        ftp.connect(uploadConfig.server, uploadConfig.port);
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }
        // Login to the FTP server
        if (!ftp.login(uploadConfig.user, uploadConfig.password)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.AUTH_FAILURE);
        }
        // Try to change directories
        if (!TextUtils.isEmpty(uploadConfig.path) && !ftp.changeWorkingDirectory(uploadConfig.path)) {
            Log.v(TAG, "Upload: could not change path to " + uploadConfig.path);
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);
        }

        // set the file type to be read as a binary file
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        // Upload the file
        is = new FileInputStream(uploadConfig.file);
        long before = System.currentTimeMillis();
        long txBytesBefore = TrafficStats.getTotalTxBytes();
        if (!ftp.storeFile(uploadConfig.file.getName(), is)) {
            ftp.disconnect();
            Log.v(TAG, "Upload: could not store file to " + uploadConfig.path + ". Error code: "
                    + ftp.getReplyCode() + ", error string: " + ftp.getReplyString());
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }

        // Calculate stats
        long after = System.currentTimeMillis();
        long txBytesAfter = TrafficStats.getTotalTxBytes();
        ftp.logout();
        ftp.disconnect();
        Log.v(TAG, "Upload complete");
        return new SpeedTestResult(txBytesAfter - txBytesBefore, uploadConfig.file.length(), after - before,
                SpeedTestStatus.SUCCESS);
    } catch (SocketException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } catch (IOException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } finally {
        IoUtil.closeSilently(is);
    }
}

From source file:jcr.FTPParser.java

public FTPParser(String host, int port, String user, String pass, String root, Session session) {
    this.session = session;
    jcrServerNodePath = "/downloadservers/" + host;
    try {//ww  w  . j  av a  2  s . c o m
        client = new FTPClient();
        client.setControlEncoding("UTF-8");
        client.connect(host, port);
        client.login(user, pass);
        parse(root);
        session.save();
    } catch (Exception ex) {
        logger.log(Level.SEVERE, null, ex);
    }
}

From source file:ftp.FTPtask.java

/**
 * Upload a file to a FTP server//from   ww  w  .j a v a 2 s.  co  m
  * @param FTPADDR, ?  ?
  * @param user,   
  * @param password,   
 * @param PathOnFtp,      -  /upload/touch.dat
 * @param FilenameOnLocalMachine,       -  C:/somefile.txt
 */

public static void UploadFileOnFtp(String FTPADDR, String user, String password, String PathOnFtp,
        String FilenameOnLocalMachine) {
    FTPClient client = new FTPClient();

    FileInputStream fis = null;

    try {
        client.connect(FTPADDR);
        client.login(user, password);

        // Create an InputStream of the file to be uploaded

        String filename = FilenameOnLocalMachine;
        fis = new FileInputStream(filename);

        // Store file to server

        client.storeFile(PathOnFtp, fis);
        client.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:fr.lille1.car.burihabwa.rest.utils.FTPAdapterImpl.java

public FTPAdapterImpl(final String host, final int port, final String username, final String password) {
    this.host = host;
    this.port = port;
    this.username = username;
    this.password = password;
    this.client = new FTPClient();
}

From source file:com.discursive.jccook.net.FTPExample.java

public void start() throws IOException {

    FTPClient client = new FTPClient();
    OutputStream outStream = null;

    try {/*  w  ww  . ja v a2 s  .c  om*/
        client.connect("ftp.ibiblio.org");
        client.login("anonymous", "");

        String remoteFile = "/pub/micro/commodore/schematics/computers/c64/c64bus.gif";
        outStream = new FileOutputStream("c64bus.gif");

        client.retrieveFile(remoteFile, outStream);
    } catch (IOException ioe) {
        System.out.println("Error communicating with FTP server.");
    } finally {
        IOUtils.closeQuietly(outStream);
        try {
            client.disconnect();
        } catch (IOException e) {
            System.out.println("Problem disconnecting from FTP server");
        }
    }

    secondExample();

}

From source file:net.sf.ufsc.ftp.FtpProvider.java

/**
 * @see net.sf.ufsc.Provider#createSession(java.net.URI)
 *///from   w w  w. j  av  a2s  . c  om
public Session createSession(URI uri) throws IOException {
    return new FtpSession(uri, new FTPClient());
}

From source file:core.MusicStreaming.java

public void play() throws JavaLayerException, IOException {

    ftpClient = new FTPClient();
    ftpClient.connect(server, port);//ww w . ja v  a2s  .c o m
    ftpClient.login(user, pass);
    ftpClient.enterLocalPassiveMode();
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    System.out.println(ftpClient.getListHiddenFiles());
    engine = ftpClient.initiateListParsing();

    files = engine.getFiles();

    for (int i = 0; i < files.length; i++) {
        System.out.println(i + "  " + files[i].getName());
    }

    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNext()) {

        int i = scanner.nextInt();
        song = "/" + files[i].getName();
        System.out.println("curently playing " + i);
        //        song = "/Bondhu Tomar Chokher Majhe.mp3";

        if (!isFirst) {
            System.out.println("trying to stop");
            mp3player.close();
            mp3player.getPosition();
            in.close();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    isFirst = false;
                    in = new BufferedInputStream(ftpClient.retrieveFileStream(song));
                    mp3player = new Player(in);
                    mp3player.play();
                } catch (Exception ex) {
                    Logger.getLogger(MusicStreaming.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }).start();

    }

}