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

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

Introduction

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

Prototype

public int getReplyCode() 

Source Link

Document

Returns the integer value of the reply code of the last FTP reply.

Usage

From source file:adams.core.io.lister.FtpDirectoryLister.java

/**
 * Returns a new client for the host defined in the options.
 *
 * @return      the client, null if failed to create
 *//*from   w  ww. j a  v a  2s .  c o m*/
protected FTPClient newClient() {
    FTPClient result;
    int reply;

    try {
        result = new FTPClient();
        result.addProtocolCommandListener(this);
        result.connect(m_Host);
        reply = result.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            getLogger().severe("FTP server refused connection: " + reply);
        } else {
            if (!result.login(m_User, m_Password.getValue())) {
                getLogger().severe("Failed to connect to '" + m_Host + "' as user '" + m_User + "'");
            } else {
                if (m_UsePassiveMode)
                    result.enterLocalPassiveMode();
                if (m_UseBinaryMode)
                    result.setFileType(FTPClient.BINARY_FILE_TYPE);
            }
        }
    } catch (Exception e) {
        Utils.handleException(this, "Failed to connect to '" + m_Host + "' as user '" + m_User + "': ", e);
        result = null;
    }

    return result;
}

From source file:com.jmeter.alfresco.utils.FtpUtils.java

/**
 * Upload file.//w ww.jav  a 2 s.c om
 *
 * @param ftpClient the ftp client
 * @param frmLocalFilePath the frm local file path
 * @param toRemoteFilePath the to remote file path
 * @return true, if successful
 * @throws IOException Signals that an I/O exception has occurred.
 */
private boolean uploadFile(final FTPClient ftpClient, final String frmLocalFilePath,
        final String toRemoteFilePath) throws IOException {

    final File localFile = new File(frmLocalFilePath);
    final InputStream inputStream = new FileInputStream(localFile);
    try {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        final boolean isFileUploaded = ftpClient.storeFile(toRemoteFilePath, inputStream);
        final int replyCode = ftpClient.getReplyCode();
        //If reply code is 550 then,Requested action not taken. File unavailable (e.g., file not found, no access).
        //If reply code is 150 then,File status okay (e.g., File found)
        //If reply code is 226 then,Closing data connection. 
        //If reply code is 426 then,Connection closed; transfer aborted. 
        LOG.debug("Reply code from remote host after storeFile(..) call: " + replyCode);
        return isFileUploaded;
    } finally {
        inputStream.close();
    }
}

From source file:com.dp2345.plugin.ftp.FtpPlugin.java

@Override
public void upload(String path, File file, String contentType) {
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
        String host = pluginConfig.getAttribute("host");
        Integer port = Integer.valueOf(pluginConfig.getAttribute("port"));
        String username = pluginConfig.getAttribute("username");
        String password = pluginConfig.getAttribute("password");
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {//from  w w  w.  j  a  va  2  s .  com
            inputStream = new FileInputStream(file);
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:com.bbytes.jfilesync.sync.ftp.FTPClientFactory.java

/**
 * Get {@link FTPClient} with initialized connects to server given in properties file
 * @return/*from w  w  w  . ja v  a  2 s.com*/
 */
public FTPClient getClientInstance() {

    ExecutorService ftpclientConnThreadPool = Executors.newSingleThreadExecutor();
    Future<FTPClient> future = ftpclientConnThreadPool.submit(new Callable<FTPClient>() {

        FTPClient ftpClient = new FTPClient();

        boolean connected;

        public FTPClient call() throws Exception {

            try {
                while (!connected) {
                    try {
                        ftpClient.connect(host, port);
                        if (!ftpClient.login(username, password)) {
                            ftpClient.logout();
                        }
                        connected = true;
                        return ftpClient;
                    } catch (Exception e) {
                        connected = false;
                    }

                }

                int reply = ftpClient.getReplyCode();
                // FTPReply stores a set of constants for FTP reply codes.
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                }

                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return ftpClient;
        }
    });

    FTPClient ftpClient = new FTPClient();
    try {
        // wait for 100 secs for acquiring conn else terminate
        ftpClient = future.get(100, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        log.info("FTP client Conn wait thread terminated!");
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
    } catch (ExecutionException e) {
        log.error(e.getMessage(), e);
    }

    ftpclientConnThreadPool.shutdownNow();
    return ftpClient;

}

From source file:com.jaeksoft.searchlib.crawler.file.process.fileInstances.FtpFileInstance.java

protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException {
    FilePathItem fpi = getFilePathItem();
    FTPClient ftp = null;
    try {// ww  w  .  j  a v  a 2  s.com
        ftp = new FTPClient();
        // For debug
        // f.addProtocolCommandListener(new PrintCommandListener(
        // new PrintWriter(System.out)));
        ftp.setConnectTimeout(120000);
        ftp.setControlKeepAliveTimeout(180);
        ftp.setDataTimeout(120000);
        ftp.connect(fpi.getHost());
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply))
            throw new IOException("FTP Error Code: " + reply);
        ftp.login(fpi.getUsername(), fpi.getPassword());
        if (!FTPReply.isPositiveCompletion(reply))
            throw new IOException("FTP Error Code: " + reply);
        if (fpi.isFtpUsePassiveMode())
            ftp.enterLocalPassiveMode();
        if (!FTPReply.isPositiveCompletion(reply))
            throw new IOException("FTP Error Code: " + reply);
        FTPClient ftpReturn = ftp;
        ftp = null;
        return ftpReturn;
    } finally {
        if (ftp != null)
            ftpQuietDisconnect(ftp);
    }
}

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();// www  . j  a v a2s  .  co  m
    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:net.paissad.jcamstream.utils.FTPUtils.java

public void estabishConnection() throws SocketException, IOException, FTPException {

    this.setFtpClient(new FTPClient());
    String errMsg;//from   ww w .j av a 2  s  .c o m

    FTPClient client = this.getFtpClient();
    PrintCommandListener listener = new PrintCommandListener(System.out);
    client.addProtocolCommandListener(listener);

    // Connects to the FTP server
    String host = this.getFtpServerHost();
    int port = this.getFtpServerPort();
    client.connect(host, port);
    if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
        client.disconnect();
        errMsg = "Unable to connect to the server " + this.getFtpServerHost();
        this.verifyReplyCode(errMsg);
    }

    // Login to the FTP server
    String username = this.getFtpUser();
    String pass = this.getFtpPassword();
    if (!client.login(username, pass)) {
        errMsg = "Unable to login to " + this.getFtpServerHost();
        this.verifyReplyCode(errMsg);
    }

    // Change the current directory
    String dirname = this.getFtpServerDir();
    if (!client.changeWorkingDirectory(dirname)) {

        System.out.println("Unable to change to the directory '" + dirname + "'.");
        System.out.println("Going to create the directory !");
        this.mkdirs(dirname);
        System.out.println("Creation of the directory is successful.");
    }

    client.changeWorkingDirectory(dirname);
    if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
        errMsg = "Unable to change to the directory : " + dirname;
        this.verifyReplyCode(errMsg);
    }

    client.pwd();
}

From source file:cn.zhuqi.mavenssh.web.util.FTPClientTemplate.java

/**
 * ftp?/*w  w w . j a  va 2  s  .c  om*/
 *
 * @param ftpClient
 * @return ?true?false
 * @throws Exception
 */
private boolean connect(FTPClient ftpClient) throws Exception {
    try {
        ftpClient.connect(host, port);

        // ?????
        int reply = ftpClient.getReplyCode();

        if (FTPReply.isPositiveCompletion(reply)) {
            //ftp?
            if (ftpClient.login(username, password)) {
                setFileType(ftpClient);
                return true;
            }
        } else {
            ftpClient.disconnect();
            throw new Exception("FTP server refused connection.");
        }
    } catch (IOException e) {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect(); //
            } catch (IOException e1) {
                throw new Exception("Could not disconnect from server.", e1);
            }

        }
        throw new Exception("Could not connect to server.", e);
    }
    return false;
}

From source file:com.microsoft.azuretools.utils.WebAppUtils.java

public static void deployArtifact(String artifactName, String artifactPath, PublishingProfile pp,
        boolean toRoot, IProgressIndicator indicator) throws IOException {
    FTPClient ftp = null;
    InputStream input = null;/* www  . ja va  2s.  c  om*/
    try {
        if (indicator != null)
            indicator.setText("Connecting to FTP server...");

        ftp = getFtpConnection(pp);

        if (indicator != null)
            indicator.setText("Uploading the application...");
        input = new FileInputStream(artifactPath);
        if (toRoot) {
            WebAppUtils.removeFtpDirectory(ftp, ftpWebAppsPath + "ROOT", indicator);
            ftp.deleteFile(ftpWebAppsPath + "ROOT.war");
            ftp.storeFile(ftpWebAppsPath + "ROOT.war", input);
        } else {
            WebAppUtils.removeFtpDirectory(ftp, ftpWebAppsPath + artifactName, indicator);
            ftp.deleteFile(artifactName + ".war");
            boolean success = ftp.storeFile(ftpWebAppsPath + artifactName + ".war", input);
            if (!success) {
                int rc = ftp.getReplyCode();
                throw new IOException("FTP client can't store the artifact, reply code: " + rc);
            }
        }
        if (indicator != null)
            indicator.setText("Logging out of FTP server...");
        ftp.logout();
    } finally {
        if (input != null)
            input.close();
        if (ftp != null && ftp.isConnected()) {
            ftp.disconnect();
        }
    }
}

From source file:com.cladonia.xngreditor.URLUtilities.java

public static InputStream open(URL url) throws IOException {
    //        System.out.println( "URLUtilities.open( "+url+")");
    InputStream stream = null;//from  w w w .  j a  v  a2 s.co  m

    String password = URLUtilities.getPassword(url);
    String username = URLUtilities.getUsername(url);

    String protocol = url.getProtocol();

    if (protocol.equals("http") || protocol.equals("https")) {
        try {
            DefaultAuthenticator authenticator = Main.getDefaultAuthenticator();

            URL newURL = new URL(URLUtilities.toString(url));

            if (authenticator != null && password != null && username != null) {
                authenticator.setPasswordAuthentication(
                        new PasswordAuthentication(username, password.toCharArray()));
            }

            stream = newURL.openStream();

            if (authenticator != null && password != null && username != null) {
                authenticator.setPasswordAuthentication(null);
            }
        } catch (Exception e) {
            //            System.out.println( "Could not use normal http connection, because of:\n"+e.getMessage());
            // try it with webdav
            WebdavResource webdav = createWebdavResource(toString(url), username, password);

            stream = webdav.getMethodData(toString(url));

            webdav.close();
        }
    } else if (protocol.equals("ftp")) {
        FTPClient client = null;
        String host = url.getHost();

        try {
            //               System.out.println( "Connecting to: "+host+" ...");

            client = new FTPClient();
            client.connect(host);

            //               System.out.println( "Connected.");

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

            if (!FTPReply.isPositiveCompletion(reply)) {
                //                  System.out.println( "Could not connect.");
                client.disconnect();
                throw new IOException("FTP Server \"" + host + "\" refused connection.");
            }

            //               System.out.println( "Logging in using: "+username+", "+password+" ...");

            if (!client.login(username, password)) {
                //                  System.out.println( "Could not log in.");
                // TODO bring up login dialog?
                client.disconnect();

                throw new IOException("Could not login to FTP Server \"" + host + "\".");
            }

            //               System.out.println( "Logged in.");

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

            //               System.out.println( "Opening file \""+url.getFile()+"\" ...");

            stream = client.retrieveFileStream(url.getFile());
            //               System.out.println( "File opened.");

            //               System.out.println( "Disconnecting ...");
            client.disconnect();
            //               System.out.println( "Disconnected.");

        } catch (IOException e) {
            if (client.isConnected()) {
                try {
                    client.disconnect();
                } catch (IOException f) {
                    // do nothing
                    e.printStackTrace();
                }
            }

            throw new IOException("Could not connect to FTP Server \"" + host + "\".");
        }

    } else if (protocol.equals("file")) {
        stream = url.openStream();
    } else {

        //unknown protocol but try anyways
        try {
            stream = url.openStream();
        } catch (IOException ioe) {

            throw new IOException("The \"" + protocol + "\" protocol is not supported.");
        }
    }

    return stream;
}