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:org.ramadda.repository.type.FtpTypeHandler.java

/**
 * _more_/*from  w  ww . j  a v  a 2s.c  o  m*/
 *
 * @param parentEntry _more_
 *
 * @return _more_
 *
 * @throws Exception _more_
 */
private FTPClient getFtpClient(Entry parentEntry) throws Exception {
    Object[] values = parentEntry.getValues();
    if (values == null) {
        return null;
    }
    String server = (String) values[COL_SERVER];
    String baseDir = (String) values[COL_BASEDIR];
    String user = (String) values[COL_USER];
    String password = (String) values[COL_PASSWORD];
    if (password != null) {
        password = getRepository().getPageHandler().processTemplate(password, false);
    } else {
        password = "";
    }
    FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect(server);
        if (user != null) {
            ftpClient.login(user, password);
        }
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            System.err.println("FTP server refused connection.");

            return null;
        }
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();

        return ftpClient;
    } catch (Exception exc) {
        System.err.println("Could not connect to ftp server:" + server + "\nError:" + exc);

        return null;
    }
}

From source file:org.ramadda.util.Utils.java

/**
 * _more_//from w ww  .ja v  a 2 s  .  co  m
 *
 * @param url _more_
 *
 * @return _more_
 *
 * @throws Exception _more_
 */
public static FTPClient makeFTPClient(URL url) throws Exception {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(url.getHost());
    ftpClient.login("anonymous", "");
    int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
        System.err.println("FTP server refused connection.");

        return null;
    }
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    ftpClient.enterLocalPassiveMode();

    return ftpClient;
}

From source file:org.runmyprocess.sec.FTP.java

private boolean connect(String host, String login, String password, int port) throws IOException {
    client.setConnectTimeout(15000);/*w w  w  . ja  v  a  2  s  .  c  om*/
    //this.client.enterLocalPassiveMode() ;
    try {
        if (!client.isConnected()) {
            LOG.log("Connecting...", Level.INFO);
            client.connect(host, port);
        }
    } catch (Exception e) {
        throw new IOException(e.toString());
    }

    int reply = client.getReplyCode();
    LOG.log("connected:" + client.getReplyString() + " replyCode:" + reply + " / "
            + FTPReply.isPositiveCompletion(reply), Level.INFO);
    if (FTPReply.isPositiveCompletion(reply)) {

        this.client.enterLocalPassiveMode();
        logged = client.login(login, password);
        LOG.log("Logged in :" + logged, Level.INFO);
        return logged;
    } else {
        throw new IOException("Error connecting to the FTP server");
    }

}

From source file:org.shept.util.FtpFileCopy.java

/**
 * @param//w  w w. j a  v a 2 s .  c o  m
 * @return
 *
 * @param config
 * @param ftpC
 * @throws SocketException
 * @throws IOException
 */
private boolean configSetup(FtpConfig config, FTPClient ftpC) throws IOException {
    boolean rc;
    ftpC.connect(config.getHostAddress(), config.getPort());
    rc = ftpC.login(config.getUserName(), config.getPassword());
    if (!rc) {
        logger.error("Ftp could not log to remote server with " + config.getUserName());
        return false;
    }
    if (StringUtils.hasText(config.getServerPath())) {
        int cwdCode = ftpC.cwd(config.getServerPath());
        if (!FTPReply.isPositiveCompletion(cwdCode)) {
            logger.error("Ftp could not change working dir to " + config.getServerPath()
                    + " - Server returned Code " + cwdCode);
            return false;
        }
    }
    rc = ftpC.setFileType(config.getFileType());
    if (!rc) {
        logger.error("Ftp could not change FileType for transmission");
        return false;
    }
    return true;
}

From source file:org.sipfoundry.preflight.FTP.java

public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService,
        InetAddress bindAddress) {
    ResultCode results = NONE;/*from   ww w  . j  av a  2s .c  om*/
    InetAddress ftpServerAddress = null;
    String testFile = new String("00D01EFFFFFE");
    String[] verificationStrings = { "LIP-68XX configuration information", "[VOIP]", "outbound_proxy_server",
            "[PROVISION]", "decrypt_key" };

    if (networkResources.configServer == null) {
        journalService.println("No FTP server provided, skipping test.\n");
        return CONFIG_SERVER_MISSING;
    }

    journalService.println("Starting FTP server test.");

    if (IPAddressUtil.isLiteralIPAddress(networkResources.configServer)) {
        try {
            ftpServerAddress = InetAddress.getByName(networkResources.configServer);
        } catch (UnknownHostException e) {
            // Should never get here.
            e.printStackTrace();
        }
        journalService.println("Using FTP server literal address: " + networkResources.configServer);
    } else {
        // Try to retrieve A RECORD for FTP server, checking each DNS server.
        SimpleResolver resolver = null;
        try {
            resolver = new SimpleResolver();
            resolver.setLocalAddress(bindAddress);
            resolver.setTimeout(timeout);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        for (InetAddress dnsServer : networkResources.domainNameServers) {
            journalService.println(
                    "Looking up FTP server address via DNS server: " + dnsServer.getCanonicalHostName());
            String targetMessage = new String("  FTP server address \"" + networkResources.configServer + "\"");
            resolver.setAddress(dnsServer);
            Lookup aLookup = null;
            try {
                aLookup = new Lookup(networkResources.configServer, Type.A);
            } catch (TextParseException e) {
                journalService.println("  is malformed.\n");
                journalService.println(targetMessage);
                return FTP_ADDRESS_MALFORMED;
            }
            aLookup.setResolver(resolver);
            Record[] aRecords = aLookup.run();
            switch (aLookup.getResult()) {
            case Lookup.SUCCESSFUL:
                if (aRecords != null) {
                    InetAddress targetAddress = ((ARecord) aRecords[0]).getAddress();
                    targetMessage += " resolves to: " + targetAddress.getHostAddress();
                    journalService.println(targetMessage);
                    if (ftpServerAddress == null) {
                        ftpServerAddress = targetAddress;
                    } else {
                        // Check that multiple lookups result in same
                        // address.
                        if (!ftpServerAddress.equals(targetAddress)) {
                            journalService.println("  FTP server address does not match prior lookup.");
                            results = MULTIPLE_CONFIG_TARGETS;
                        }
                    }
                } else {
                    targetMessage += " could not be resolved.";
                    journalService.println(targetMessage);
                    results = FTP_TARGET_UNRESOLVED;
                }
                break;
            case Lookup.UNRECOVERABLE:
                targetMessage += " [Unrecoverable error]";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TRY_AGAIN:
                targetMessage += " [Lookup timeout]";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.HOST_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TYPE_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            }
        }
    }

    if ((ftpServerAddress == null) || (results == MULTIPLE_CONFIG_TARGETS)) {
        journalService.println("Cannot recover from previous errors, aborting FTP test.\n");
        return results;
    }

    journalService.println("Beginning FTP get request of test file: " + testFile);

    // Open the FTP connection.
    FTPClient ftp = new FTPClient();
    ftp.setDefaultTimeout(timeout * 1000);
    ftp.addProtocolCommandListener(new PrintCommandListener(journalService));

    try {
        int reply;
        ftp.connect(ftpServerAddress, 21, bindAddress, bindPort);

        // After connection, check reply code to verify.
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            journalService.println("FTP client failure: " + reply + "\n");
            return FTP_CLIENT_FAILURE;
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // Ignore.
            }
        }
        journalService.println("FTP client failure: " + e.getMessage() + "\n");
        return FTP_CLIENT_FAILURE;
    }

    try {
        if (!ftp.login(ftpUser, ftpPassword)) {
            ftp.logout();
            journalService.println("FTP client unable to log in.\n");
            return FTP_GET_FAILED;
        }

        journalService.println("FTP client connected to: " + ftp.getSystemName());

        ftp.enterLocalPassiveMode();

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ftp.retrieveFile(testFile, output);

        // After receiving, check reply code to verify.
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            journalService.println("FTP get failure: " + reply + "\n");
            return FTP_GET_FAILED;
        }

        ftp.logout();

        String testFileContents = output.toString();
        boolean verified = true;
        for (String verificationString : verificationStrings) {
            if (!testFileContents.contains(verificationString)) {
                verified = false;
            }
        }
        if (verified) {
            journalService.println("File received successfully.");
        } else {
            journalService.println("File received but contents do not verify.");
            System.err.println(testFileContents);
            results = FTP_CONTENTS_FAILED;
        }
    } catch (FTPConnectionClosedException e) {
        journalService.println("FTP server closed connection prematurely.\n");
        return FTP_GET_FAILED;
    } catch (IOException e) {
        journalService.println("FTP client failure. " + e.getMessage() + "\n");
        return FTP_CLIENT_FAILURE;
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // Ignore.
            }
        }
    }

    journalService.println("");
    return results;
}

From source file:org.sipfoundry.sipxconfig.admin.ftp.FtpContextImpl.java

public void openConnection() {
    if (m_client != null) {
        return;/*w  w  w.  j av  a  2 s  .co m*/
    }
    m_client = new FTPClient();
    try {
        m_client.connect(m_host);
        int reply = m_client.getReplyCode();

        // After connection attempt, you should check the reply code to verify
        // success.
        if (!FTPReply.isPositiveCompletion(reply)) {
            closeConnection();
            throw new UserException("&message.refusedConnection");
        }
        if (!m_client.login(m_userId, m_password)) {
            closeConnection();
            throw new UserException("&message.userPass");
        }
        m_client.setFileType(FTP.BINARY_FILE_TYPE);
        m_client.enterLocalPassiveMode();
    } catch (IOException e) {
        LOG.error(e);
        throw new UserException("&message.notConnect");
    }
}

From source file:org.smartfrog.avalanche.client.sf.ftp.FTPDownload.java

public boolean loginFtpServer() throws IOException {
    int reply;//w  w w .  j a  v a 2  s  .c o m

    try {
        // Connect to FTP Server
        ftp.connect(ftpServer);
        log.info("Connecting to FTP Server : " + ftpServer);

        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            log.error("FTP Server " + ftpServer + " refused connection");
            return false;
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                log.warn("Disconnection of " + ftpServer + " failed\n", e);
            }
        }
        log.error("Connection to FTP Server " + ftpServer + " failed\n", e);
        throw e;
    }

    try {
        // Log in to the FTP Server with userName and passWord
        if (!ftp.login(userName, passWord)) {
            ftp.logout();
            log.error("Logging to " + ftpServer + " failed");
            return false;
        }

    } catch (IOException e) {
        log.error("Login to FTP Server " + ftpServer + " failed.\n", e);
    }
    log.info("FTP login successful on FTP server " + ftpServer + " for the user " + userName + ".");
    return true;
}

From source file:org.smartfrog.avalanche.server.ftp.FTPRepository.java

public void connect() throws RepositoryConnectException {

    //Connect to FTPServer
    try {/*from  w w  w. j a  v a2  s.c o m*/
        int reply;
        ftp.connect(ftpServer);
        log.info("Connecting to " + ftpServer + ".");

        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            log.error("FTP Server " + ftpServer + " refused connection");
            throw new RepositoryConnectException("FTP Server " + ftpServer + " refused connection");
        }

    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                log.warn("Disconnection of " + ftpServer + " Failed", e);
                throw new RepositoryConnectException("Disconnection of " + ftpServer + " Failed", e);
            }
        }
        log.error("Connection to FTP Server" + ftpServer + "Failed", e);
        throw new RepositoryConnectException("Connection to FTP Server " + ftpServer + " Failed", e);
    }
    //Loging to FTPServer
    try {
        if (!ftp.login(userName, password)) {
            ftp.logout();
            log.error("Logging to " + ftpServer + " failed");
            throw new RepositoryConnectException("Logging to " + ftpServer + " failed");

        }

        //Set fileType for transfer
        if (fileFormat.equalsIgnoreCase("ascii"))
            ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
        else
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

        //Change working directory
        if (path == null)
            path = ftp.printWorkingDirectory();
        else
            ftp.changeWorkingDirectory(path);
        super.filePath = path;
    } catch (IOException e) {
        log.error(ftpServer + " login Failed.", e);
        throw new RepositoryConnectException(ftpServer + " login Failed.", e);
    }

}

From source file:org.smartfrog.services.net.FTPClientImpl.java

/**
 * Sends or retrieve files over FTP using attributes specified in the
 * SmartFrog description of the component.
 *
 * @throws SmartFrogException in case of error in sending email
 * @throws RemoteException    in case of network/emi error
 *///  www  . j  ava  2 s. c om
public synchronized void sfStart() throws SmartFrogException, RemoteException {
    super.sfStart();
    try {
        ftpClient = new FTPClient();
        int reply;

        // get password from password provider
        password = pwdProvider.getPassword();

        ftpClient.connect(ftpServer);

        reply = ftpClient.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            throw new SmartFrogLifecycleException("FTP Server:[" + ftpServer + "] refused connection");
        }

        //login
        if (!ftpClient.login(user, password)) {
            ftpClient.logout();
        }

        //check type of file transfer
        if (BINARY.equals(transferMode)) {
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        ftpClient.enterLocalPassiveMode();

        if (GET.equals(transferType)) {
            getFiles(remoteFileList, localFileList);
        } else if (PUT.equals(transferType)) {
            putFiles(remoteFileList, localFileList);
        } else {
            throw new SmartFrogLifecycleException("Unsupported transfer type:" + transferType);
        }
        //logout
        ftpClient.logout();

        // check if it should terminate by itself
        if (shouldTerminate) {
            TerminationRecord termR = TerminationRecord.normal("FTP finished: ", sfCompleteName());
            TerminatorThread terminator = new TerminatorThread(this, termR);
            terminator.start();
        }
    } catch (FTPConnectionClosedException e) {
        throw new SmartFrogLifecycleException("Server Closed Connection" + e, e);
    } catch (IOException ioe) {
        throw new SmartFrogLifecycleException(ioe);
    } finally {
        disconnectQuietly();
    }
}

From source file:org.sofun.platform.opta.ftp.FTPClientWrapper.java

/**
 * Establishes a connection w/ the FTP server.
 * /*from w w w. j  av  a 2s  .c o m*/
 * @throws OptaException
 */
public void connect() throws OptaException {
    if (client == null || !client.isAvailable()) {
        client = new FTPClient();
    }
    try {
        client.connect(host, port);
        int reply = client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            client.disconnect();
            throw new OptaException("FTP server refused connection.");
        }
    } catch (SocketException e) {
        throw new OptaException(e.getMessage());
    } catch (IOException e) {
        if (client.isConnected()) {
            try {
                client.disconnect();
            } catch (IOException f) {
                // do nothing: just spit stack trace.
                f.printStackTrace();
            }
        }
        throw new OptaException(e.getMessage());
    }
    try {
        if (!client.login(username, password)) {
            client.logout();
            throw new OptaException("Cannot login...");
        }
        client.enterLocalPassiveMode();
    } catch (Exception e) {
        throw new OptaException(e.getMessage());
    }
}