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.FTPClientTemplate.java

/**
 * FTPClient//from  w  ww.  ja  v a  2 s  . c o m
 *
 * @throws Exception
 */
private FTPClient getFTPClient() throws Exception {
    if (ftpClientThreadLocal.get() != null && ftpClientThreadLocal.get().isConnected()) {
        return ftpClientThreadLocal.get();
    } else {
        FTPClient ftpClient = new FTPClient(); //FtpClient
        ftpClient.setControlEncoding(encoding); //

        connect(ftpClient); //ftp?

        //passive?
        if (passiveMode) {
            ftpClient.enterLocalPassiveMode();
        }
        setFileType(ftpClient); //

        try {
            ftpClient.setSoTimeout(clientTimeout);
        } catch (SocketException e) {
            throw new Exception("Set timeout error.", e);
        }
        ftpClientThreadLocal.set(ftpClient);
        return ftpClient;
    }
}

From source file:de.quadrillenschule.azocamsyncd.ftpservice.FTPConnection.java

public void simplyConnect(int fileType) {
    boolean conn = false;
    do {// w ww.java2  s. c om
        try {
            // if (ftpclient != null) {
            close();
            // }
            ftpclient = new FTPClient();
            if (fileType == FTP.BINARY_FILE_TYPE) {
                ftpclient.setDefaultTimeout(LONG_TIMEOUT);
            } else {
                ftpclient.setDefaultTimeout(TIMEOUT);
            }
            ftpclient.connect(getLastWorkingConnection());

            ftpclient.enterLocalPassiveMode();
            ftpclient.setFileType(fileType);
            conn = true;

        } catch (Exception ex) {
            close();
            conn = false;
            checkConnection(false);
        }
    } while (!conn);
}

From source file:it.baywaylabs.jumpersumo.utility.FTPDownloadImage.java

/**
 * Background thread that download photo from the robot and prepare it for local processing or for Twitter reply.<br />
 * This method is called when invoke <b>execute()</b>.<br />
 * Do not invoke manually. Use: <i>new FTPDownloadImage().execute("");</i>
 *
 * @param params The parameters of the task. They can be <b>"local"</b> or <b>"twitter"</b>.
 * @return Null if everything was going ok.
 * @see #onPreExecute()/*w w  w . j a va  2  s  .c  om*/
 * @see #onPostExecute
 * @see #publishProgress
 */
@Override
protected String doInBackground(String... params) {

    String resultFileName = "";
    try {
        mFTPClient = new FTPClient();
        // connecting to the host
        mFTPClient.connect(host, port);

        // Now check the reply code, if positive mean connection success
        if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {

            // Login using username & password
            boolean status = mFTPClient.login(user, pass);
            mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
            mFTPClient.enterLocalPassiveMode();

            mFTPClient.changeWorkingDirectory(Constants.DIR_ROBOT_MEDIA);
            FTPFile[] fileList = mFTPClient.listFiles();
            long timestamp = 0l;
            String nameFile = "";
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isFile() && fileList[i].getTimestamp().getTimeInMillis() > timestamp) {
                    timestamp = fileList[i].getTimestamp().getTimeInMillis();
                    nameFile = fileList[i].getName();
                }
            }
            Log.d(TAG, "File da scaricare: " + nameFile);

            mFTPClient.enterLocalActiveMode();
            File folder = new File(Constants.DIR_ROBOT_IMG);
            OutputStream outputStream = null;
            boolean success = true;
            if (!folder.exists()) {
                success = folder.mkdir();
            }

            if (params.length != 0 && !"".equals(nameFile))
                if ("local".equals(params[0])) {
                    try {
                        outputStream = new FileOutputStream(folder.getAbsolutePath() + "/" + nameFile);
                        success = mFTPClient.retrieveFile(nameFile, outputStream);
                    } catch (Exception e) {
                        return e.getMessage();
                    } finally {
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    }
                    if (success) {
                        resultFileName = nameFile;
                        ContentResolver contentResolver = context.getContentResolver();
                        Bitmap bitmap = BitmapFactory.decodeFile(folder.getAbsolutePath() + "/" + nameFile);
                        Log.e(TAG, "FileName: " + folder.getAbsolutePath() + "/" + nameFile);
                        MediaStore.Images.Media.insertImage(contentResolver, bitmap, nameFile,
                                "Jumper Sumo Photo");

                        mFTPClient.deleteFile(nameFile);

                        File[] list = folder.listFiles();
                        for (int i = 0; i < list.length; i++) {
                            if (nameFile.equals(list[i].getName()))
                                list[i].delete();
                        }

                    }
                } else if ("twitter".equals(params[0])) {
                    try {
                        outputStream = new FileOutputStream(folder.getAbsolutePath() + "/" + nameFile);
                        success = mFTPClient.retrieveFile(nameFile, outputStream);
                    } catch (Exception e) {
                        return e.getMessage();
                    } finally {
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    }
                    if (success) {
                        resultFileName = nameFile;
                        mFTPClient.deleteFile(nameFile);
                    }
                }
        }
    } catch (Exception e) {
        return e.getMessage();
    } finally {
        if (mFTPClient != null) {
            try {
                mFTPClient.logout();
                mFTPClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    if (!"".equals(resultFileName))
        return resultFileName;
    return null;
}

From source file:be.thomasmore.controller.FileController.java

public String uploadFile() throws IOException {
    String server = "logic.sinners.be";
    int port = 21;
    String user = "logic_java";
    String pass = "scoretracker";

    FTPClient ftpClient = new FTPClient();
    try {//from   ww w  . jav a2 s.c  o  m
        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        String firstRemoteFile = getFileName(part);
        InputStream inputStream = part.getInputStream();

        System.out.println("Bestand uploaden");
        boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
        inputStream.close();
        if (done) {
            System.out.println("Het bestand is succesvol upgeload.");
            statusMessage = "De gegevens werden succesvol ingeladen.";
        }

    } catch (IOException ex) {
        System.out.println("Fout: " + ex.getMessage());
        statusMessage = "Er is een fout opgetreden: " + ex.getMessage();
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /*
     //De bestandsnaam uit het bestand (part) halen
     String fileName = getFileName(part);
     System.out.println("***** fileName: " + fileName);
            
     String basePath = "C:" + File.separator + "data" + File.separator;
            
     File outputFilePath = new File(basePath + fileName);
            
     //Streams aanmaken om het upgeloade bestand naar de destination te kopiren
     InputStream inputStream = null;
     OutputStream outputStream = null;
     try {
     inputStream = part.getInputStream();
     outputStream = new FileOutputStream(outputFilePath);
            
     int read = 0;
     final byte[] bytes = new byte[1024];
     while ((read = inputStream.read(bytes)) != -1) {
     outputStream.write(bytes, 0, read);
     }
     statusMessage = "De gegevens werden succesvol ingeladen.";
     } catch (IOException e) {
     e.printStackTrace();
     statusMessage = "Er is een fout opgetreden.";
     } finally {
     if (outputStream != null) {
     outputStream.close();
     }
     if (inputStream != null) {
     inputStream.close();
     }
     }*/
    leesExcel();

    return null;
}

From source file:autonomouspathplanner.ftp.FTP.java

/**
 * Attempts to connect to the server//  w  w w.j av  a2  s  .  c om
 * @return true if connection is established, and false if the connection is failed
 */
public boolean connectToServer() {
    client = new FTPClient();
    try {
        client.connect(IP, port);
        int replyCode = client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            System.out.println("Operation failed. Server reply code: " + replyCode);
            return false;
        }
        boolean success = client.login(user, pass);
        if (!success) {
            System.out.println("Could not login to the server");
            return false;
        } else {
            System.out.println("LOGGED IN SERVER");
        }

        client.enterLocalPassiveMode();
        client.setFileType(FTPClient.BINARY_FILE_TYPE); //We need to check what type to do
    } catch (IOException ex) {
        return false;
    }
    return true;
}

From source file:cn.zhuqi.mavenssh.web.util.test.FtpTest.java

/**
 * Description: FTP?//from   w ww  .j a v a 2s  . c  om
 *
 * @Version1.0
 * @param url FTP?hostname
 * @param port FTP??
 * @param username FTP?
 * @param password FTP?
 * @param remotePath FTP?
 * @param fileName ???
 * @param localPath ??
 * @return
 */
public static boolean downloadFile(String url, int port, String username, String password, String remotePath,
        String fileName, String localPath) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        // FTP?
        if (port > -1) {
            ftp.connect(url, port);
        } else {
            ftp.connect(url);
        }
        ftp.login(username, password);//
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        ftp.changeWorkingDirectory(remotePath);//FTP?
        FTPFile[] fs = ftp.listFiles();
        for (FTPFile ff : fs) {
            if (ff.getName().equals(fileName)) {
                File localFile = new File(localPath + "/" + ff.getName());
                OutputStream is = new FileOutputStream(localFile);
                ftp.retrieveFile(ff.getName(), is);
                is.close();
            }
        }

        ftp.logout();
        success = true;
    } catch (IOException e) {
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
            }
        }
    }
    return success;
}

From source file:com.haha01haha01.harail.DatabaseDownloader.java

private Boolean downloadFile(String server, int portNumber, String user, String password, String filename,
        File localFile) throws IOException {
    FTPClient ftp = null;//w  w w.j a  va2  s.co m

    try {
        ftp = new FTPClient();
        ftp.setBufferSize(1024 * 1024);
        ftp.connect(server, portNumber);
        Log.d(NAME, "Connected. Reply: " + ftp.getReplyString());
        if (!ftp.login(user, password)) {
            return false;
        }
        Log.d(NAME, "Logged in");
        if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
            return false;
        }
        Log.d(NAME, "Downloading");
        ftp.enterLocalPassiveMode();

        OutputStream outputStream = null;
        boolean success = false;
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
            success = ftp.retrieveFile(filename, outputStream);
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }

        return success;
    } finally {
        if (ftp != null) {
            ftp.logout();
            ftp.disconnect();
        }
    }
}

From source file:com.tobias.vocabulary_trainer.UpdateVocabularies.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_vocabularies_layout);
    prefs = getSharedPreferences(USER_PREFERENCE, Activity.MODE_PRIVATE);
    serverAdresseEditText = (EditText) findViewById(R.id.server_adresse_edit_text);
    serverUsernameEditText = (EditText) findViewById(R.id.server_username_edit_text);
    serverPasswordEditText = (EditText) findViewById(R.id.server_password_edit_text);
    serverPortEditText = (EditText) findViewById(R.id.server_port_edit_text);
    serverFileEditText = (EditText) findViewById(R.id.server_file_edit_text);
    localFileEditText = (EditText) findViewById(R.id.local_file_edit_text);

    vocabularies = new VocabularyData(this);
    System.out.println("before updateUIFromPreferences();");
    updateUIFromPreferences();/*from ww w  .  j a  va 2s  .  c  om*/
    System.out.println("after updateUIFromPreferences();");

    final Button ServerOkButton = (Button) findViewById(R.id.server_ok);
    ServerOkButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            System.out.println("ServerOKButton pressed");
            savePreferences();
            InputStream in;
            String serverAdresse = serverAdresseEditText.getText().toString();
            String serverUsername = serverUsernameEditText.getText().toString();
            String serverPassword = serverPasswordEditText.getText().toString();
            int serverPort = Integer.parseInt(serverPortEditText.getText().toString());
            String serverFile = serverFileEditText.getText().toString();

            FTPClient ftp;
            ftp = new FTPClient();
            try {
                int reply;
                System.out.println("try to connect to ftp server");
                ftp.connect(serverAdresse, serverPort);
                System.out.print(ftp.getReplyString());
                // After connection attempt, you should check the reply code to verify
                // success.
                reply = ftp.getReplyCode();
                if (FTPReply.isPositiveCompletion(reply)) {
                    System.out.println("connected to ftp server");
                } else {
                    ftp.disconnect();
                    System.out.println("FTP server refused connection.");
                }

                // transfer files
                System.out.println("try to login");
                ftp.login(serverUsername, serverPassword);
                System.out.println("current working directory: " + ftp.printWorkingDirectory());
                System.out.println("try to start downloading");
                in = ftp.retrieveFileStream(serverFile);
                // files transferred
                //write to database and textfile on sdcard
                vocabularies.readVocabularies(in, false);
                ftp.logout();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                        // do nothing
                    }
                }
            }
            //               settings.populateSpinners();
            finish();
        }
    });
    final Button LocalFileOkButton = (Button) findViewById(R.id.local_file_ok);
    LocalFileOkButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            File f = new File(Environment.getExternalStorageDirectory(),
                    localFileEditText.getText().toString());
            savePreferences();
            vocabularies.readVocabularies(f, false);
            //               settings.populateSpinners();
            finish();
        }
    });
    final Button CancelButton = (Button) findViewById(R.id.Cancel);
    CancelButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
    vocabularies.close();
}

From source file:com.glaf.core.util.FtpUtils.java

/**
 * ???FTP?// w  w  w  .j  a  va2s.co m
 */
public static FTPClient connectServer(String prefix) {
    String ip = conf.get(prefix + ".ftp.host", "127.0.0.1");
    int port = conf.getInt(prefix + ".ftp.port", 21);
    String user = conf.get(prefix + ".ftp.user", "admin");
    String password = conf.get(prefix + ".ftp.password", "admin");
    try {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(ip, port);
        ftpClient.login(user, password);
        ftpClientLocal.set(ftpClient);
        logger.info("login success!");
        return ftpClient;
    } catch (IOException ex) {
        ex.printStackTrace();
        logger.error("login failed", ex);
        throw new RuntimeException(ex);
    }
}

From source file:biz.gabrys.lesscss.extended.compiler.source.FtpSource.java

private FTPClient connect() {
    final FTPClient connection = new FTPClient();
    try {/*from w ww . jav a2 s.  c om*/
        connection.setAutodetectUTF8(true);
        connection.connect(url.getHost(), port);
        connection.enterLocalActiveMode();
        if (!connection.login("anonymous", "gabrys.biz Extended LessCSS Compiler")) {
            throw new SourceException(
                    String.format("Cannot login as anonymous user, reason %s", connection.getReplyString()));
        }
        if (!FTPReply.isPositiveCompletion(connection.getReplyCode())) {
            throw new SourceException(String.format("Cannot download source \"%s\", reason: %s", url,
                    connection.getReplyString()));
        }
        connection.enterLocalPassiveMode();
        connection.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (final IOException e) {
        disconnect(connection);
        throw new SourceException(e);
    }
    return connection;
}