Example usage for org.apache.commons.net.ftp FTPReply isPositiveCompletion

List of usage examples for org.apache.commons.net.ftp FTPReply isPositiveCompletion

Introduction

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

Prototype

public static boolean isPositiveCompletion(int reply) 

Source Link

Document

Determine if a reply code is a positive completion response.

Usage

From source file:ConnectionInfo.java

private void createActions() {
    // Up one level - local dir
    actionUpLocalDir = new Action() {
        public void run() {
            if (localDirBrowser.getInput() == null)
                return;
            File dir = ((File) localDirBrowser.getInput()).getParentFile();
            if (dir != null) {
                localDirBrowser.setInput(dir);
                labelPathLocal.setText("Path: " + dir);
            }/*w w w.ja va  2  s.c o m*/
        }
    };
    actionUpLocalDir.setText("Up");
    actionUpLocalDir.setToolTipText("Up one level - local dir");
    actionUpLocalDir.setImageDescriptor(ImageDescriptor.createFromFile(null, "icons/ftp/up.gif"));

    // browse for local dir
    actionBrowseLocalDir = new Action() {
        public void run() {
            DirectoryDialog dialog = new DirectoryDialog(getShell());
            String path = dialog.open();
            if (path == null)
                return;
            File file = new File(path);
            localDirBrowser.setInput(file);
            labelPathLocal.setText("Path: " + file);
        }
    };
    actionBrowseLocalDir.setText("Browse...");
    actionBrowseLocalDir.setToolTipText("Browse local directory");
    actionBrowseLocalDir.setImageDescriptor(ImageDescriptor.createFromFile(null, "icons/ftp/browse.gif"));

    // connect
    actionConnect = new Action() {
        public void run() {
            if (connectionDialog == null)
                connectionDialog = new ConnectionDialog(FTPWindow.this);
            if (connectionDialog.open() == Dialog.OK) {
                connectionInfo = connectionDialog.getConnectionInfo();
                if (connectionInfo == null) {
                    logError("Failed to get connection information.");
                } else {
                    // connects to remote host.
                    logMessage("Connecting to " + connectionInfo.host, true);
                    try {
                        ftp.connect(connectionInfo.host, connectionInfo.port);
                        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode()))
                            throw new RuntimeException("FTP server refused connection.");
                        logMessage("Connected to " + connectionInfo.host, true);
                    } catch (Exception e) {
                        logError(e.toString());
                        return;
                    }
                    try {
                        // logins in.
                        if (ftp.login(connectionInfo.username, connectionInfo.password)) {
                            logMessage("Logged in as user: " + connectionInfo.username, true);
                        }
                        // gets current working directory.
                        labelPathRemote.setText("Path: " + ftp.printWorkingDirectory());

                        // Lists files.
                        FTPFile[] files = ftp.listFiles();
                        remoteDirBrowser.setInput(files);

                    } catch (IOException e1) {
                        logError(e1.getMessage());
                        try {
                            ftp.disconnect();
                        } catch (IOException e2) {
                            // 
                        }
                    }
                }
            }
        }
    };
    actionConnect.setText("Connect");
    actionConnect.setToolTipText("Connect to remote host");
    actionConnect.setImageDescriptor(ImageDescriptor.createFromFile(null, "icons/ftp/connect.gif"));

    // disconnect
    actionDisconnect = new Action() {
        public void run() {
            try {
                ftp.logout();
                ftp.disconnect();
            } catch (Exception e) {
                logError(e.toString());
            }
        }
    };
    actionDisconnect.setText("Disconnect");
    actionDisconnect.setToolTipText("Disconnect from remote host");
    actionDisconnect.setImageDescriptor(ImageDescriptor.createFromFile(null, "icons/ftp/stop.gif"));

    // up one level - remote dir.
    actionUpRemoteDir = new Action() {
        public void run() {
            try {
                if (ftp.changeToParentDirectory()) {
                    // gets current working directory.
                    labelPathRemote.setText("Path: " + ftp.printWorkingDirectory());

                    // Lists files.
                    FTPFile[] files = ftp.listFiles();
                    remoteDirBrowser.setInput(files);
                }
            } catch (Exception e) {
                logError(e.toString());
            }
        }
    };
    actionUpRemoteDir.setText("Up");
    actionUpRemoteDir.setToolTipText("Up one level - remote dir");
    actionUpRemoteDir.setImageDescriptor(ImageDescriptor.createFromFile(null, "icons/ftp/up.gif"));

    actionDisplayAbout = new Action() {
        public void run() {
            MessageDialog.openInformation(getShell(), "About",
                    "FTP Client v1.0\nAll right reserved by Jack Li Guojie.");
        }
    };
    actionDisplayAbout.setText("About");
    actionDisplayAbout.setImageDescriptor(ImageDescriptor.createFromFile(null, "icons/ftp/about.gif"));

    actionExit = new Action() {
        public void run() {
            if (!MessageDialog.openConfirm(getShell(), "Confirm", "Are you sure you want to exit?"))
                return;
            try {
                ftp.disconnect();
            } catch (Exception e) {
                // ignore.
            }
            close();
        }
    };
    actionExit.setText("Exit");
    actionExit.setImageDescriptor(ImageDescriptor.createFromFile(null, "icons/ftp/close.gif"));

}

From source file:com.claim.controller.FileTransferController.java

public boolean uploadMutiFilesWithFTPS(ObjFileTransfer ftpObj) throws Exception {
    FTPSClient ftpsClient = null;//from w  w w  .j  a v  a 2  s  .  co  m
    int replyCode;
    boolean completed = false;
    try {

        FtpProperties properties = new ResourcesProperties().loadFTPProperties();

        try {
            ftpsClient = new FTPSClient(properties.getFtp_protocal(), properties.isFtp_impicit());
            //ftpsClient.setAuthValue(ConstantFtp.FTPS_PROTOCAL);
            ftpsClient.setDataTimeout(ConstantFtp.FTP_TIMEOUT);

            ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            System.out.print(ftpsClient.getReplyString());

            ftpsClient.connect(properties.getFtp_server(), properties.getFtp_port());
            FtpUtil.showServerReply(ftpsClient);

        } catch (ConnectException ex) {
            FtpUtil.showServerReply(ftpsClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("ConnectException: " + ex.getMessage());
            ex.printStackTrace();
        } catch (SocketException ex) {
            FtpUtil.showServerReply(ftpsClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("SocketException: " + ex.getMessage());
            ex.printStackTrace();
        } catch (UnknownHostException ex) {
            FtpUtil.showServerReply(ftpsClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("UnknownHostException: " + ex.getMessage());
            ex.printStackTrace();
        }

        replyCode = ftpsClient.getReplyCode();
        FtpUtil.showServerReply(ftpsClient);

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftpsClient.disconnect();
            Console.LOG("Exception in connecting to FTP Serve ", 0);
            throw new Exception("Exception in connecting to FTP Server");
        } else {
            Console.LOG("Success in connecting to FTP Serve ", 1);
        }

        try {
            boolean success = ftpsClient.login(properties.getFtp_username(), properties.getFtp_password());

            FtpUtil.showServerReply(ftpsClient);
            if (!success) {
                throw new Exception("Could not login to the FTP server.");
            } else {
                Console.LOG("login to the FTP server. Successfully ", 1);
            }
            //ftpClient.enterLocalPassiveMode();
        } catch (FTPConnectionClosedException ex) {
            Console.LOG(ex.getMessage(), 0);
            FtpUtil.showServerReply(ftpsClient);
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        }

        ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpsClient.execPBSZ(0);

        //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory();
        String workingDirectoryReportType = properties.getFtp_remote_directory() + File.separator
                + ftpObj.getFtp_report_type();
        FtpUtil.ftpCreateDirectoryTree(ftpsClient, workingDirectoryReportType);
        FtpUtil.showServerReply(ftpsClient);

        String workingDirectoryStmp = workingDirectoryReportType + File.separator + ftpObj.getFtp_stmp();
        FtpUtil.ftpCreateDirectoryTree(ftpsClient, workingDirectoryStmp);
        FtpUtil.showServerReply(ftpsClient);

        // APPROACH #2: uploads second file using an OutputStream
        File files = new File(ftpObj.getFtp_directory_path());

        for (File file : files.listFiles()) {
            if (file.isFile()) {
                System.out.println("file ::" + file.getName());
                InputStream in = new FileInputStream(file);
                ftpsClient.changeWorkingDirectory(workingDirectoryStmp);
                completed = ftpsClient.storeFile(file.getName(), in);
                in.close();
                Console.LOG(
                        "  " + file.getName() + " ",
                        1);
                FtpUtil.showServerReply(ftpsClient);
            }
        }
        Console.LOG(" ?... ", 1);

        //completed = ftpClient.completePendingCommand();
        FtpUtil.showServerReply(ftpsClient);
        completed = true;
        ftpsClient.disconnect();

    } catch (IOException ex) {
        Console.LOG(ex.getMessage(), 0);
        FtpUtil.showServerReply(ftpsClient);
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftpsClient.isConnected()) {
                ftpsClient.logout();
                ftpsClient.disconnect();
            }
        } catch (IOException ex) {
            FtpUtil.showServerReply(ftpsClient);
            Console.LOG(ex.getMessage(), 0);
            ex.printStackTrace();
        }
    }
    return completed;
}

From source file:ch.cyberduck.core.ftp.FTPClient.java

private boolean initFeatureMap() throws IOException {
    if (features == null) {
        // Don't create map here, because next line may throw exception
        final int reply = feat();
        if (FTPReply.NOT_LOGGED_IN == reply) {
            return false;
        } else {/*from w w  w  . ja  v  a2 s.  c  o  m*/
            // we init the map here, so we don't keep trying if we know the command will fail
            features = new HashMap<String, Set<String>>();
        }
        boolean success = FTPReply.isPositiveCompletion(reply);
        if (!success) {
            return false;
        }
        for (String l : getReplyStrings()) {
            if (l.startsWith(" ")) { // it's a FEAT entry
                String key;
                String value = "";
                int varsep = l.indexOf(' ', 1);
                if (varsep > 0) {
                    key = l.substring(1, varsep);
                    value = l.substring(varsep + 1);
                } else {
                    key = l.substring(1);
                }
                key = key.toUpperCase(Locale.ROOT);
                Set<String> entries = features.get(key);
                if (entries == null) {
                    entries = new HashSet<String>();
                    features.put(key, entries);
                }
                entries.add(value);
            }
        }
    }
    return true;
}

From source file:ddf.test.itests.catalog.TestFtp.java

private FTPSClient createSecureClient(boolean setKeystore) throws Exception {
    FTPSClient ftps = new FTPSClient();

    if (setKeystore) {
        KeyManager keyManager = KeyManagerUtils.createClientKeyManager(
                new File(System.getProperty("javax.net.ssl.keyStore")),
                System.getProperty("javax.net.ssl.keyStorePassword"));
        ftps.setKeyManager(keyManager);/*www. j a  v a2  s .co m*/
    }

    int attempts = 0;
    while (true) {
        try {
            ftps.connect(FTP_SERVER, Integer.parseInt(FTP_PORT.getPort()));
            break;
        } catch (SocketException e) {
            // a socket exception can be thrown if the ftp server is still in the process of coming up
            // or down
            Thread.sleep(1000);
            if (attempts++ > 30) {
                throw e;
            }
        }
    }

    showServerReply(ftps);
    int connectionReply = ftps.getReplyCode();
    if (!FTPReply.isPositiveCompletion(connectionReply)) {
        fail("FTP server refused connection: " + connectionReply);
    }

    boolean success = ftps.login(USERNAME, PASSWORD);
    showServerReply(ftps);
    if (!success) {
        fail("Could not log in to the FTP server.");
    }

    ftps.enterLocalPassiveMode();
    ftps.setControlKeepAliveTimeout(300);
    ftps.setFileType(FTP.BINARY_FILE_TYPE);

    return ftps;
}

From source file:ilarkesto.integration.ftp.FtpClient.java

public synchronized void connect() {
    if (client != null && client.isConnected())
        return;/*from   ww  w.  j  a  v a2s . c  o m*/

    client = new FTPClient();

    log.info("Connecting", server);
    try {
        client.connect(server, port != null ? port.intValue() : client.getDefaultPort());
        if (!FTPReply.isPositiveCompletion(client.getReplyCode()))
            throw new RuntimeException("Nagative reply after connection: " + client.getReplyString());
    } catch (Exception ex) {
        log.error("FTP connection failed:", server, "->", ex);
        return;
    }

    LoginData loginData = login.getLoginData();
    try {
        if (!client.login(loginData.getLogin(), loginData.getPassword()))
            throw new RuntimeException("FTP-Login fehlgeschlagen: " + server);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    try {
        client.setFileType(FTPClient.BINARY_FILE_TYPE);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    client.enterLocalPassiveMode();
    client.setAutodetectUTF8(false);
    client.setCharset(Charset.forName(IO.UTF_8));
}

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

public void uploadFile(File fileLocal, String remoteFile) {
    if (!ftpclient.isConnected()) {
        errorText = "not connected";
        succeeded = false;/*from w  w  w .j  a  v a2 s .c o  m*/
        return;
    }

    FileInputStream fis = null;
    BufferedInputStream bis = null;
    try {

        ftpclient.setAutodetectUTF8(true);

        fis = new FileInputStream(fileLocal);
        bis = new BufferedInputStream(fis);
        ftpclient.storeFile(remoteFile, bis);
        bis.close();

        errorCode = ftpclient.getReplyCode();
        succeeded = FTPReply.isPositiveCompletion(errorCode);

    } catch (Exception e) {
        errorCode = ftpclient.getReplyCode();
        errorText = e.getMessage();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
            }
        }
        setStatusData();
    }
}

From source file:ch.cyberduck.core.ftp.FTPSession.java

@Override
public void login(final HostPasswordStore keychain, final LoginCallback prompt, final CancelCallback cancel)
        throws BackgroundException {
    try {//from   w  w  w. j ava2 s  .c  o m
        if (client.login(host.getCredentials().getUsername(), host.getCredentials().getPassword())) {
            if (host.getProtocol().isSecure()) {
                client.execPBSZ(0);
                // Negotiate data connection security
                client.execPROT(preferences.getProperty("ftp.tls.datachannel"));
            }
            if ("UTF-8".equals(host.getEncoding())) {
                if (client.hasFeature("UTF8")) {
                    if (!FTPReply.isPositiveCompletion(client.sendCommand("OPTS UTF8 ON"))) {
                        log.warn(
                                String.format("Failed to negotiate UTF-8 charset %s", client.getReplyString()));
                    }
                }
            }
            final TimeZone zone = host.getTimezone();
            if (log.isInfoEnabled()) {
                log.info(String.format("Reset parser to timezone %s", zone));
            }
            String system = null; //Unknown
            try {
                system = client.getSystemType();
                if (system.toUpperCase(Locale.ROOT).contains(FTPClientConfig.SYST_NT)) {
                    casesensitivity = Case.insensitive;
                }
            } catch (IOException e) {
                log.warn(String.format("SYST command failed %s", e.getMessage()));
            }
            listService = new FTPListService(this, keychain, prompt, system, zone);
            if (client.hasFeature(FTPCmd.MFMT.getCommand())) {
                timestamp = new FTPMFMTTimestampFeature(this);
            } else {
                timestamp = new FTPUTIMETimestampFeature(this);
            }
            permission = new FTPUnixPermissionFeature(this);
            if (client.hasFeature("SITE", "SYMLINK")) {
                symlink = new FTPSymlinkFeature(this);
            }
        } else {
            throw new FTPExceptionMappingService()
                    .map(new FTPException(this.getClient().getReplyCode(), this.getClient().getReplyString()));
        }
    } catch (IOException e) {
        throw new FTPExceptionMappingService().map(e);
    }
}

From source file:fr.acxio.tools.agia.ftp.DefaultFtpClientFactory.java

public FTPClient getFtpClient() throws IOException {
    FTPClient aClient = new FTPClient();

    // Debug output
    // aClient.addProtocolCommandListener(new PrintCommandListener(new
    // PrintWriter(System.out), true));

    if (activeExternalIPAddress != null) {
        aClient.setActiveExternalIPAddress(activeExternalIPAddress);
    }//from w  w w.  ja v a  2s. c  om
    if (activeMinPort != null && activeMaxPort != null) {
        aClient.setActivePortRange(activeMinPort, activeMaxPort);
    }
    if (autodetectUTF8 != null) {
        aClient.setAutodetectUTF8(autodetectUTF8);
    }
    if (bufferSize != null) {
        aClient.setBufferSize(bufferSize);
    }
    if (charset != null) {
        aClient.setCharset(charset);
    }
    if (connectTimeout != null) {
        aClient.setConnectTimeout(connectTimeout);
    }
    if (controlEncoding != null) {
        aClient.setControlEncoding(controlEncoding);
    }
    if (controlKeepAliveReplyTimeout != null) {
        aClient.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    if (controlKeepAliveTimeout != null) {
        aClient.setControlKeepAliveTimeout(controlKeepAliveTimeout);
    }
    if (dataTimeout != null) {
        aClient.setDataTimeout(dataTimeout);
    }
    if (defaultPort != null) {
        aClient.setDefaultPort(defaultPort);
    }
    if (defaultTimeout != null) {
        aClient.setDefaultTimeout(defaultTimeout);
    }
    if (fileStructure != null) {
        aClient.setFileStructure(fileStructure);
    }
    if (keepAlive != null) {
        aClient.setKeepAlive(keepAlive);
    }
    if (listHiddenFiles != null) {
        aClient.setListHiddenFiles(listHiddenFiles);
    }
    if (parserFactory != null) {
        aClient.setParserFactory(parserFactory);
    }
    if (passiveLocalIPAddress != null) {
        aClient.setPassiveLocalIPAddress(passiveLocalIPAddress);
    }
    if (passiveNatWorkaround != null) {
        aClient.setPassiveNatWorkaround(passiveNatWorkaround);
    }
    if (proxy != null) {
        aClient.setProxy(proxy);
    }
    if (receieveDataSocketBufferSize != null) {
        aClient.setReceieveDataSocketBufferSize(receieveDataSocketBufferSize);
    }
    if (receiveBufferSize != null) {
        aClient.setReceiveBufferSize(receiveBufferSize);
    }
    if (remoteVerificationEnabled != null) {
        aClient.setRemoteVerificationEnabled(remoteVerificationEnabled);
    }
    if (reportActiveExternalIPAddress != null) {
        aClient.setReportActiveExternalIPAddress(reportActiveExternalIPAddress);
    }
    if (sendBufferSize != null) {
        aClient.setSendBufferSize(sendBufferSize);
    }
    if (sendDataSocketBufferSize != null) {
        aClient.setSendDataSocketBufferSize(sendDataSocketBufferSize);
    }
    if (strictMultilineParsing != null) {
        aClient.setStrictMultilineParsing(strictMultilineParsing);
    }
    if (tcpNoDelay != null) {
        aClient.setTcpNoDelay(tcpNoDelay);
    }
    if (useEPSVwithIPv4 != null) {
        aClient.setUseEPSVwithIPv4(useEPSVwithIPv4);
    }

    if (systemKey != null) {
        FTPClientConfig aClientConfig = new FTPClientConfig(systemKey);
        if (defaultDateFormat != null) {
            aClientConfig.setDefaultDateFormatStr(defaultDateFormat);
        }
        if (recentDateFormat != null) {
            aClientConfig.setRecentDateFormatStr(recentDateFormat);
        }
        if (serverLanguageCode != null) {
            aClientConfig.setServerLanguageCode(serverLanguageCode);
        }
        if (shortMonthNames != null) {
            aClientConfig.setShortMonthNames(shortMonthNames);
        }
        if (serverTimeZoneId != null) {
            aClientConfig.setServerTimeZoneId(serverTimeZoneId);
        }
        aClient.configure(aClientConfig);
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Connecting to : {}", host);
    }

    if (port == null) {
        aClient.connect(host);
    } else {
        aClient.connect(host, port);
    }

    int aReplyCode = aClient.getReplyCode();

    if (!FTPReply.isPositiveCompletion(aReplyCode)) {
        aClient.disconnect();
        throw new IOException("Cannot connect to " + host + ". Returned code : " + aReplyCode);
    }

    try {
        if (localPassiveMode) {
            aClient.enterLocalPassiveMode();
        }

        boolean aIsLoggedIn = false;
        if (account == null) {
            aIsLoggedIn = aClient.login(username, password);
        } else {
            aIsLoggedIn = aClient.login(username, password, account);
        }
        if (!aIsLoggedIn) {
            throw new IOException(aClient.getReplyString());
        }
    } catch (IOException e) {
        aClient.disconnect();
        throw e;
    }

    if (fileTransferMode != null) {
        aClient.setFileTransferMode(fileTransferMode);
    }
    if (fileType != null) {
        aClient.setFileType(fileType);
    }

    return aClient;
}

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

public boolean siteCmd(String cmd) {
    if (!ftpclient.isConnected()) {
        errorText = "not connected";
        succeeded = false;//from  w w w  . ja  va 2 s . com
        return false;
    }

    boolean bResult = false;
    try {
        bResult = ftpclient.sendSiteCommand(cmd);
        errorCode = ftpclient.getReplyCode();
        succeeded = FTPReply.isPositiveCompletion(errorCode);
    } catch (Exception e) {
        errorCode = ftpclient.getReplyCode();
        errorText = e.getMessage();
    } finally {
        setStatusData();
    }

    return bResult;
}

From source file:com.unispezi.cpanelremotebackup.ftp.FTPClient.java

/**
 * Checks result code of FTP command, logs and throws exception on failure
 *
 * @param replyCode  expected reply code
 * @param logString  log prefix to log// w w  w . j  ava  2s .com
 * @param knownSuccesState if false, will treat action as failed even if result code showed success
 */
private void checkResult(int replyCode, String logString, boolean knownSuccesState) {
    if (FTPReply.isPositiveCompletion(replyCode)) {
        if (knownSuccesState) {
            Log.info(logString + " successful");
        } else {
            Log.error(logString + " failed");
            throw new FTPException(logString + " failed");
        }
    } else {
        Log.error(logString + " failed with reply code " + replyCode);
        if (ftp.getReplyCode() == 421) { //"Connection already closed"
            isLoggedIn = false;
        }
        throw new FTPException(logString + " failed with reply code " + replyCode);
    }
}