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:com.maxl.java.aips2sqlite.AllDown.java

public void downZurRose() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {//ww w  .ja v  a 2s  . com
        FileInputStream access = new FileInputStream(Constants.DIR_ZURROSE + "/access.ami.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(access, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            // Semicolon is used as a separator
            String[] gln = line.split(";");
            if (gln.length > 2) {
                if (gln[0].equals("P_ywesee")) {
                    fl = gln[0];
                    fp = gln[1];
                    fs = gln[2];
                }
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FTPClient ftp_client = new FTPClient();
    try {
        ftp_client.connect(fs, 21);
        ftp_client.login(fl, fp);
        ftp_client.enterLocalPassiveMode();
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        System.out.println("- Connected to server " + fs + "...");

        String[] working_dir = { "ywesee out", "../ywesee in" };

        for (int i = 0; i < working_dir.length; ++i) {
            // Set working directory
            ftp_client.changeWorkingDirectory(working_dir[i]);
            int reply = ftp_client.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp_client.disconnect();
                System.err.println("FTP server refused connection.");
                return;
            }
            // Get list of filenames
            FTPFile[] ftpFiles = ftp_client.listFiles();
            if (ftpFiles != null && ftpFiles.length > 0) {
                // ... then download all csv files
                for (FTPFile f : ftpFiles) {
                    String remote_file = f.getName();
                    if (remote_file.endsWith("csv")) {
                        String local_file = remote_file;
                        if (remote_file.startsWith("Artikelstamm"))
                            local_file = Constants.CSV_FILE_DISPO_ZR;
                        OutputStream os = new FileOutputStream(Constants.DIR_ZURROSE + "/" + local_file);
                        System.out.print("- Downloading " + remote_file + " from server " + fs + "... ");
                        boolean done = ftp_client.retrieveFile(remote_file, os);
                        if (done)
                            System.out.println("success.");
                        else
                            System.out.println("error.");
                        os.close();
                    }
                }
            }
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java

/**
 * @see it.greenvulcano.util.remotefs.RemoteManager#rm(String, String, java.util.Map)
 *//*  w  w  w .jav  a  2 s  .c o  m*/
@Override
public boolean rm(String remoteDirectory, String entryNamePattern, Map<String, String> optProperties)
        throws RemoteManagerException {
    checkConnected();

    boolean oldAutoConnect = isAutoconnect();
    setAutoconnect(false);

    boolean result = false;
    try {
        if (remoteDirectory != null) {
            changeWorkingDirectory(remoteDirectory);
        }

        String[] filenames = ftpClient.listNames();
        int detectedFiles = (filenames != null ? filenames.length : 0);
        FTPFile[] results = ftpClient.listFiles();
        int parsedFiles = (results != null ? results.length : 0);
        if (detectedFiles != parsedFiles) {
            logger.warn("Some of all of the detected (" + detectedFiles + ") file entries couldn't be parsed ("
                    + parsedFiles + "), recursive delete may fail");
        }

        if (results != null) {
            RegExFileFilter fileFilter = new RegExFileFilter(entryNamePattern, RegExFileFilter.ALL, -1);
            for (FTPFile currFTPFile : results) {
                if (currFTPFile != null) {
                    if (fileFilter.accept(currFTPFile)) {
                        if (currFTPFile.isDirectory()) {
                            result = rm(currFTPFile.getName(), ".*", optProperties); // remove all sub-directory content
                            ftpClient.changeToParentDirectory();
                            if (result) {
                                ftpClient.removeDirectory(currFTPFile.getName());
                                int reply = ftpClient.getReplyCode();
                                if (FTPReply.isPositiveCompletion(reply)) {
                                    logger.debug("Remote directory " + currFTPFile.getName() + " deleted.");
                                    result = true;
                                } else {
                                    logger.warn("FTP Server NEGATIVE response: ");
                                    logServerReply(Level.WARN);
                                }
                            }
                        } else {
                            ftpClient.deleteFile(currFTPFile.getName());
                            int reply = ftpClient.getReplyCode();
                            if (FTPReply.isPositiveCompletion(reply)) {
                                logger.debug("Remote file " + currFTPFile.getName() + " deleted.");
                                result = true;
                            } else {
                                logger.warn("FTP Server NEGATIVE response: ");
                                logServerReply(Level.WARN);
                            }
                        }

                        if (!result) {
                            break;
                        }
                    }
                }
            }
        }
        return result;
    } catch (IOException exc) {
        throw new RemoteManagerException("I/O error", exc);
    } catch (Exception exc) {
        throw new RemoteManagerException("Generic error", exc);
    } finally {
        setAutoconnect(oldAutoConnect);
        if (isAutoconnect()) {
            disconnect();
        }
    }
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downDesitin() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {//from w  w  w. j av a2 s  .c  om
        FileInputStream access = new FileInputStream(Constants.DIR_DESITIN + "/access.ami.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(access, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            // Semicolon is used as a separator
            String[] gln = line.split(";");
            if (gln.length > 2) {
                if (gln[0].equals("ftp_amiko")) {
                    fl = gln[0];
                    fp = gln[1];
                    fs = gln[2];
                }
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FTPClient ftp_client = new FTPClient();
    try {
        ftp_client.connect(fs, 21);
        ftp_client.login(fl, fp);
        ftp_client.enterLocalPassiveMode();
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        System.out.println("- Connected to server " + fs + "...");

        // Set working directory
        String working_dir = "ywesee_in";
        ftp_client.changeWorkingDirectory(working_dir);
        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }
        // Get list of filenames
        FTPFile[] ftpFiles = ftp_client.listFiles();
        if (ftpFiles != null && ftpFiles.length > 0) {
            // ... then download all csv files
            for (FTPFile f : ftpFiles) {
                String remote_file = f.getName();
                if (remote_file.endsWith("csv")) {
                    String local_file = remote_file;
                    if (remote_file.startsWith("Kunden"))
                        local_file = Constants.FILE_CUST_DESITIN;
                    if (remote_file.startsWith("Artikel"))
                        local_file = Constants.FILE_ARTICLES_DESITIN;
                    OutputStream os = new FileOutputStream(Constants.DIR_DESITIN + "/" + local_file);
                    System.out.print("- Downloading " + remote_file + " from server " + fs + "... ");
                    boolean done = ftp_client.retrieveFile(remote_file, os);
                    if (done)
                        System.out.println("success.");
                    else
                        System.out.println("error.");
                    os.close();
                }
            }
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java

/**
 * @see it.greenvulcano.util.remotefs.RemoteManager#mv(String, String,
 *      String, java.util.Map)//from  w  w  w .j a va  2  s.  c o m
 */
@Override
public boolean mv(String remoteParentDirectory, String oldEntryName, String newEntryName,
        Map<String, String> optProperties) throws RemoteManagerException {
    checkConnected();

    boolean result = false;
    try {
        if (remoteParentDirectory != null) {
            changeWorkingDirectory(remoteParentDirectory);
        }
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.rename(oldEntryName, newEntryName);

        int reply = ftpClient.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            logger.debug("Remote entry " + oldEntryName + " renamed to " + newEntryName + ".");
            result = true;
        } else {
            logger.warn("FTP Server NEGATIVE response: ");
            logServerReply(Level.WARN);
        }
        return result;
    } catch (IOException exc) {
        throw new RemoteManagerException("I/O error", exc);
    } catch (Exception exc) {
        throw new RemoteManagerException("Generic error", exc);
    } finally {
        if (isAutoconnect()) {
            disconnect();
        }
    }
}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * Establishes a data connection with the FTP server, returning
 * a Socket for the connection if successful.  If a restart
 * offset has been set with {@link #setRestartOffset(long)},
 * a REST command is issued to the server with the offset as
 * an argument before establishing the data connection.  Active
 * mode connections also cause a local PORT command to be issued.
 * <p>/*ww w  . j  a va2 s  .  c  o  m*/
 * @param command  The text representation of the FTP command to send.
 * @param arg The arguments to the FTP command.  If this parameter is
 *             set to null, then the command is sent with no argument.
 * @return A Socket corresponding to the established data connection.
 *         Null is returned if an FTP protocol error is reported at
 *         any point during the establishment and initialization of
 *         the connection.
 * @exception IOException  If an I/O error occurs while either sending a
 *      command to the server or receiving a reply from the server.
 * @since 3.1
 */
protected Socket _openDataConnection_(String command, String arg) throws IOException {
    if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE
            && __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE) {
        return null;
    }

    final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address;

    Socket socket;

    if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE) {
        // if no activePortRange was set (correctly) -> getActivePort() = 0
        // -> new ServerSocket(0) -> bind to any free local port
        ServerSocket server = _serverSocketFactory_.createServerSocket(getActivePort(), 1, getHostAddress());

        try {
            // Try EPRT only if remote server is over IPv6, if not use PORT,
            // because EPRT has no advantage over PORT on IPv4.
            // It could even have the disadvantage,
            // that EPRT will make the data connection fail, because
            // today's intelligent NAT Firewalls are able to
            // substitute IP addresses in the PORT command,
            // but might not be able to recognize the EPRT command.
            if (isInet6Address) {
                if (!FTPReply.isPositiveCompletion(eprt(getReportHostAddress(), server.getLocalPort()))) {
                    return null;
                }
            } else {
                if (!FTPReply.isPositiveCompletion(port(getReportHostAddress(), server.getLocalPort()))) {
                    return null;
                }
            }

            if ((__restartOffset > 0) && !restart(__restartOffset)) {
                return null;
            }

            if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
                return null;
            }

            // For now, let's just use the data timeout value for waiting for
            // the data connection.  It may be desirable to let this be a
            // separately configurable value.  In any case, we really want
            // to allow preventing the accept from blocking indefinitely.
            if (__dataTimeout >= 0) {
                server.setSoTimeout(__dataTimeout);
            }
            socket = server.accept();

            // Ensure the timeout is set before any commands are issued on the new socket
            if (__dataTimeout >= 0) {
                socket.setSoTimeout(__dataTimeout);
            }
            if (__receiveDataSocketBufferSize > 0) {
                socket.setReceiveBufferSize(__receiveDataSocketBufferSize);
            }
            if (__sendDataSocketBufferSize > 0) {
                socket.setSendBufferSize(__sendDataSocketBufferSize);
            }
        } finally {
            server.close();
        }
    } else { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE

        // Try EPSV command first on IPv6 - and IPv4 if enabled.
        // When using IPv4 with NAT it has the advantage
        // to work with more rare configurations.
        // E.g. if FTP server has a static PASV address (external network)
        // and the client is coming from another internal network.
        // In that case the data connection after PASV command would fail,
        // while EPSV would make the client succeed by taking just the port.
        boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address;
        if (attemptEPSV && epsv() == FTPReply.ENTERING_EPSV_MODE) {
            _parseExtendedPassiveModeReply(_replyLines.get(0));
        } else {
            if (isInet6Address) {
                return null; // Must use EPSV for IPV6
            }
            // If EPSV failed on IPV4, revert to PASV
            if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) {
                return null;
            }
            _parsePassiveModeReply(_replyLines.get(0));
        }

        socket = _socketFactory_.createSocket();
        if (__receiveDataSocketBufferSize > 0) {
            socket.setReceiveBufferSize(__receiveDataSocketBufferSize);
        }
        if (__sendDataSocketBufferSize > 0) {
            socket.setSendBufferSize(__sendDataSocketBufferSize);
        }
        if (__passiveLocalHost != null) {
            socket.bind(new InetSocketAddress(__passiveLocalHost, 0));
        }

        // For now, let's just use the data timeout value for waiting for
        // the data connection.  It may be desirable to let this be a
        // separately configurable value.  In any case, we really want
        // to allow preventing the accept from blocking indefinitely.
        if (__dataTimeout >= 0) {
            socket.setSoTimeout(__dataTimeout);
        }

        socket.connect(new InetSocketAddress(__passiveHost, __passivePort), connectTimeout);
        if ((__restartOffset > 0) && !restart(__restartOffset)) {
            socket.close();
            return null;
        }

        if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
            socket.close();
            return null;
        }
    }

    if (__remoteVerificationEnabled && !verifyRemote(socket)) {
        socket.close();

        throw new IOException("Host attempting data connection " + socket.getInetAddress().getHostAddress()
                + " is not same as server " + getRemoteAddress().getHostAddress());
    }

    return socket;
}

From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java

/**
 * @see it.greenvulcano.util.remotefs.RemoteManager#mkdir(String, String, java.util.Map)
 */// ww  w. j  a  v  a  2 s  .c o m
@Override
public boolean mkdir(String remoteParentDirectory, String remoteDirectory, Map<String, String> optProperties)
        throws RemoteManagerException {
    checkConnected();

    boolean result = false;
    try {
        if (remoteParentDirectory != null) {
            changeWorkingDirectory(remoteParentDirectory);
        }

        ftpClient.makeDirectory(remoteDirectory);
        logger.debug(
                "Remote directory " + remoteDirectory + " created into " + ftpClient.printWorkingDirectory());

        int reply = ftpClient.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            logger.debug("Remote directory " + remoteDirectory + " created");
            result = true;
        } else {
            logger.warn("Could not create remote directory " + remoteDirectory
                    + " (FTP Server NEGATIVE response):");
            logServerReply(Level.WARN);
        }
        return result;
    } catch (IOException exc) {
        throw new RemoteManagerException("I/O error", exc);
    } catch (Exception exc) {
        throw new RemoteManagerException("Generic error", exc);
    } finally {
        if (isAutoconnect()) {
            disconnect();
        }
    }
}

From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java

/**
 * Changes current working directory on the remote FTP server.
 * //from  w  ww . j av a  2  s. co m
 * @param remoteDirectory
 *        the new working directory
 * @throws RemoteManagerException
 *         if any error occurs
 */
private void changeWorkingDirectory(String remoteDirectory) throws RemoteManagerException {
    logger.debug("Changing remote working directory to " + remoteDirectory + "...");
    try {
        ftpClient.changeWorkingDirectory(remoteDirectory);
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new RemoteManagerException(
                    "FTP server refused remote working directory change: " + ftpClient.getReplyString());
        }
        logger.debug("Current working directory is: " + ftpClient.printWorkingDirectory());
    } catch (RemoteManagerException exc) {
        throw exc;
    } catch (IOException exc) {
        throw new RemoteManagerException("I/O error", exc);
    }
}

From source file:com.microsoft.intellij.forms.CreateWebSiteForm.java

private void copyWebConfigForCustom(WebSiteConfiguration config) throws AzureCmdException {
    if (config != null) {
        AzureManager manager = AzureManagerImpl.getManager(project);
        WebSitePublishSettings webSitePublishSettings = manager.getWebSitePublishSettings(
                config.getSubscriptionId(), config.getWebSpaceName(), config.getWebSiteName());
        // retrieve ftp publish profile
        WebSitePublishSettings.FTPPublishProfile ftpProfile = null;
        for (WebSitePublishSettings.PublishProfile pp : webSitePublishSettings.getPublishProfileList()) {
            if (pp instanceof WebSitePublishSettings.FTPPublishProfile) {
                ftpProfile = (WebSitePublishSettings.FTPPublishProfile) pp;
                break;
            }// w w w  .  j  a  v a  2 s. c o m
        }

        if (ftpProfile != null) {
            FTPClient ftp = new FTPClient();
            try {
                URI uri = null;
                uri = new URI(ftpProfile.getPublishUrl());
                ftp.connect(uri.getHost());
                final int replyCode = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(replyCode)) {
                    ftp.disconnect();
                }
                if (!ftp.login(ftpProfile.getUserName(), ftpProfile.getPassword())) {
                    ftp.logout();
                }
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                if (ftpProfile.isFtpPassiveMode()) {
                    ftp.enterLocalPassiveMode();
                }
                ftp.deleteFile(ftpPath + message("configName"));
                String tmpPath = String.format("%s%s%s", System.getProperty("java.io.tmpdir"), File.separator,
                        message("configName"));
                File file = new File(tmpPath);
                if (file.exists()) {
                    file.delete();
                }

                WAEclipseHelperMethods.copyFile(WAHelper.getCustomJdkFile(message("configName")), tmpPath);
                String jdkFolderName = "";
                if (customJDKUser.isSelected()) {
                    String url = customUrl.getText();
                    jdkFolderName = url.substring(url.lastIndexOf("/") + 1, url.length());
                    jdkFolderName = jdkFolderName.substring(0, jdkFolderName.indexOf(".zip"));
                } else {
                    String cloudVal = WindowsAzureProjectManager
                            .getCloudValue((String) jdkNames.getSelectedItem(), AzurePlugin.cmpntFile);
                    jdkFolderName = cloudVal.substring(cloudVal.indexOf("\\") + 1, cloudVal.length());
                }
                String jdkPath = "%HOME%\\site\\wwwroot\\jdk\\" + jdkFolderName;
                String serverPath = "%programfiles(x86)%\\" + WAHelper
                        .generateServerFolderName(config.getJavaContainer(), config.getJavaContainerVersion());
                WebAppConfigOperations.prepareWebConfigForCustomJDKServer(tmpPath, jdkPath, serverPath);
                InputStream input = new FileInputStream(tmpPath);
                ftp.storeFile(ftpPath + message("configName"), input);
                cleanup(ftp);
                ftp.logout();
            } catch (Exception e) {
                AzurePlugin.log(e.getMessage(), e);
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
    }
}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * Login to the FTP server using the provided username and password.
 * <p>// www. j  a  v  a2  s  .  c  o  m
 * @param username The username to login under.
 * @param password The password to use.
 * @return True if successfully completed, false if not.
 * @exception FTPConnectionClosedException
 *      If the FTP server prematurely closes the connection as a result
 *      of the client being idle or some other reason causing the server
 *      to send FTP reply code 421.  This exception may be caught either
 *      as an IOException or independently as itself.
 * @exception IOException  If an I/O error occurs while either sending a
 *      command to the server or receiving a reply from the server.
 */
public boolean login(String username, String password) throws IOException {

    user(username);

    if (FTPReply.isPositiveCompletion(_replyCode)) {
        return true;
    }

    // If we get here, we either have an error code, or an intermmediate
    // reply requesting password.
    if (!FTPReply.isPositiveIntermediate(_replyCode)) {
        return false;
    }

    return FTPReply.isPositiveCompletion(pass(password));
}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * Login to the FTP server using the provided username, password,
 * and account.  If no account is required by the server, only
 * the username and password, the account information is not used.
 * <p>//from  ww w . j  a v  a 2s  .  c  o m
 * @param username The username to login under.
 * @param password The password to use.
 * @param account  The account to use.
 * @return True if successfully completed, false if not.
 * @exception FTPConnectionClosedException
 *      If the FTP server prematurely closes the connection as a result
 *      of the client being idle or some other reason causing the server
 *      to send FTP reply code 421.  This exception may be caught either
 *      as an IOException or independently as itself.
 * @exception IOException  If an I/O error occurs while either sending a
 *      command to the server or receiving a reply from the server.
 */
public boolean login(String username, String password, String account) throws IOException {
    user(username);

    if (FTPReply.isPositiveCompletion(_replyCode)) {
        return true;
    }

    // If we get here, we either have an error code, or an intermmediate
    // reply requesting password.
    if (!FTPReply.isPositiveIntermediate(_replyCode)) {
        return false;
    }

    pass(password);

    if (FTPReply.isPositiveCompletion(_replyCode)) {
        return true;
    }

    if (!FTPReply.isPositiveIntermediate(_replyCode)) {
        return false;
    }

    return FTPReply.isPositiveCompletion(acct(account));
}