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:facturacion.ftp.FtpServer.java

public static InputStream getTokenInputStream(String remote_file_ruta) {
    FTPClient ftpClient = new FTPClient();
    try {/*from  w  w w.  j a  va 2s. c o  m*/
        //ftpClient.connect("127.0.0.1", 21 );
        //ftpClient.login("erpftp", "Tribut@2014");
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        int reply = ftpClient.getReplyCode();

        System.out.println("Respuesta recibida de conexin FTP:" + reply);

        if (!FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Imposible conectarse al servidor");
            //return -1;
        } else {
            System.out.println("se conecto al servidor");
        }
        //ftpClient.enterLocalPassiveMode();
        // crear directorio
        //OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(file_ruta));
        //System.out.println("File #1 has been downloaded successfully. 1");
        //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\firmado2.p12");
        //InputStream is = fis;
        System.out.println("File rutaqq=" + "1-/" + remote_file_ruta);
        InputStream is = ftpClient.retrieveFileStream(remote_file_ruta);

        if (is == null)
            System.out.println("File #1 es null token");
        else
            System.out.println("File #1 no es null token");

        //return ftpClient.retrieveFileStream(remote_file_ruta);
        return is;
    } catch (IOException ex) {
        System.out.println("File #1 has been downloaded successfully. 222");
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            System.out.println("File #1 has been downloaded successfully. 3");
            return null;
            //ex.printStackTrace();
        }
    }
    return null;
}

From source file:com.ephesoft.dcma.ftp.service.FTPServiceImpl.java

/**
 * API to download a particular directory from FTP Server.
 * //  w  w w .ja  va 2  s .co m
 * @param sourceDirName {@link String} - Name of the source directory to be copied.
 * @param destDirectoryPath {@link String} - Full path where directory need to be copied.
 * @param retryCounter - Start with zero.
 * @param isDeletedFTPServerSourceContent - set true for deleted the ftp server content.
 * @throws FTPDataDownloadException if any error occurs while downloading the file.
 */
@Override
public void downloadDirectory(final String sourceDirName, final String destDirectoryPath,
        final int numberOfRetryCounter, boolean isDeletedFTPServerSourceContent)
        throws FTPDataDownloadException {
    boolean isValid = true;
    if (sourceDirName == null) {
        isValid = false;
        LOGGER.error(var_source_dir);
        throw new FTPDataDownloadException(var_source_dir);
    }
    if (destDirectoryPath == null) {
        isValid = false;
        LOGGER.error(var_source_des);
        throw new FTPDataDownloadException(var_source_des);
    }
    if (isValid) {
        FTPClient client = new FTPClient();
        String outputFileName = null;
        File file = new File(destDirectoryPath);
        if (!file.exists()) {
            file.mkdir();
        }
        try {
            createConnection(client);
            int reply = client.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                LOGGER.info("Starting File Download...");
            } else {
                LOGGER.error("Invalid Connection to FTP server. Disconnecting from FTP server....");
                client.disconnect();
                isValid = false;
                throw new FTPDataDownloadException(
                        "Invalid Connection to FTP server. Disconnecting from FTP server....");
            }
            if (isValid) {
                client.setFileType(FTP.BINARY_FILE_TYPE);
                String ftpDirectory = EphesoftStringUtil.concatenate(uploadBaseDir, File.separator,
                        sourceDirName);
                LOGGER.info("Downloading files from FTP server");
                try {
                    FTPUtil.retrieveFiles(client, ftpDirectory, destDirectoryPath);
                } catch (IOException e) {
                    int retryCounter = numberOfRetryCounter;
                    LOGGER.info("Retrying download Attempt#-" + (retryCounter + 1));
                    if (retryCounter < numberOfRetries) {
                        retryCounter = retryCounter + 1;
                        downloadDirectory(sourceDirName, destDirectoryPath, retryCounter,
                                isDeletedFTPServerSourceContent);
                    } else {
                        LOGGER.error("Error in getting file from FTP server :" + outputFileName);
                    }
                }
                if (isDeletedFTPServerSourceContent) {
                    FTPUtil.deleteExistingFTPData(client, ftpDirectory, true);
                }
            }
        } catch (FileNotFoundException e) {
            LOGGER.error("Error in generating output Stream for file :" + outputFileName);
        } catch (SocketException e) {
            LOGGER.error("Could not connect to FTP Server-" + ftpServerURL + e);
        } catch (IOException e) {
            LOGGER.error("Could not connect to FTP Server-" + ftpServerURL + e);
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                LOGGER.error("Error in disconnecting from FTP server." + e);
            }
        }
    }
}

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

public String getCurrentDirectory() {
    if (!ftpclient.isConnected()) {
        errorText = "not connected";
        succeeded = false;/*from   w  ww  .ja  va2 s  .  c om*/
        return null;
    }

    String curdir = null;
    try {
        curdir = ftpclient.printWorkingDirectory();
        errorCode = ftpclient.getReplyCode();
        succeeded = FTPReply.isPositiveCompletion(errorCode);
    } catch (Exception e) {
        errorCode = ftpclient.getReplyCode();
        errorText = e.getMessage();
    } finally {
        setStatusData();
    }

    return curdir;
}

From source file:at.beris.virtualfile.client.ftp.FtpClient.java

@Override
public void deleteDirectory(final String path) throws IOException {
    LOGGER.debug("deleteDirectory (path : {})", path);
    executionHandler(new Callable<Void>() {
        @Override//from  www. ja  v a  2 s .  c o  m
        public Void call() throws Exception {
            int replyCode = ftpClient.rmd(path);
            String replyText = ftpClient.getReplyString();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                LOGGER.warn("Unexpected Reply (Code: {}, Text: '{}'", replyCode, replyText);
            }
            return null;
        }
    });
}

From source file:com.limegroup.gnutella.archive.ArchiveContribution.java

/**
 * //  w w w . ja v  a  2  s.c  om
 * @throws UnknownHostException
 *         If the hostname cannot be resolved.
 *         
 * @throws SocketException
 *         If the socket timeout could not be set.
 *         
 * @throws FTPConnectionClosedException
 *         If the connection is closed by the server.
 *         
 * @throws LoginFailedException
 *         If the login fails.
 *         
 * @throws DirectoryChangeFailedException
 *         If changing to the directory provided by the internet
 *         archive fails.
 *         
 * @throws CopyStreamException
 *         If an I/O error occurs while in the middle of
 *         transferring a file.
 *         
 * @throws IOException
 *         If an I/O error occurs while sending a command or
 *         receiving a reply from the server
 *         
 * @throws IllegalStateException
 *          If the contribution object is not ready to upload
 *          (no username, password, server, etc. set)
 *          or if java's xml parser is configured badly
 */

public void upload()
        throws UnknownHostException, SocketException, FTPConnectionClosedException, LoginFailedException,
        DirectoryChangeFailedException, CopyStreamException, RefusedConnectionException, IOException {

    final int NUM_XML_FILES = 2;
    final String META_XML_SUFFIX = "_meta.xml";
    final String FILES_XML_SUFFIX = "_files.xml";

    final String username = getUsername();
    final String password = getPassword();

    if (getFtpServer() == null) {
        throw new IllegalStateException("ftp server not set");
    }
    if (getFtpPath() == null) {
        throw new IllegalStateException("ftp path not set");
    }
    if (username == null) {
        throw new IllegalStateException("username not set");
    }
    if (password == null) {
        throw new IllegalStateException("password not set");
    }

    // calculate total number of files and bytes

    final String metaXmlString = serializeDocument(getMetaDocument());
    final String filesXmlString = serializeDocument(getFilesDocument());

    final byte[] metaXmlBytes = metaXmlString.getBytes();
    final byte[] filesXmlBytes = filesXmlString.getBytes();

    final int metaXmlLength = metaXmlBytes.length;
    final int filesXmlLength = filesXmlBytes.length;

    final Collection files = getFiles();

    final int totalFiles = NUM_XML_FILES + files.size();

    final String[] fileNames = new String[totalFiles];
    final long[] fileSizes = new long[totalFiles];

    final String metaXmlName = getIdentifier() + META_XML_SUFFIX;
    fileNames[0] = metaXmlName;
    fileSizes[0] = metaXmlLength;

    final String filesXmlName = getIdentifier() + FILES_XML_SUFFIX;
    fileNames[1] = filesXmlName;
    fileSizes[1] = filesXmlLength;

    int j = 2;
    for (Iterator i = files.iterator(); i.hasNext();) {
        final File f = (File) i.next();
        fileNames[j] = f.getRemoteFileName();
        fileSizes[j] = f.getFileSize();
        j++;
    }

    // init the progress mapping
    for (int i = 0; i < fileSizes.length; i++) {
        _fileNames2Progress.put(fileNames[i], new UploadFileProgress(fileSizes[i]));
        _totalUploadSize += fileSizes[i];
    }

    FTPClient ftp = new FTPClient();

    try {
        // first connect

        if (isCancelled()) {
            return;
        }
        ftp.enterLocalPassiveMode();

        if (isCancelled()) {
            return;
        }
        ftp.connect(getFtpServer());

        final int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new RefusedConnectionException(getFtpServer() + "refused FTP connection");
        }
        // now login
        if (isCancelled()) {
            return;
        }
        if (!ftp.login(username, password)) {
            throw new LoginFailedException();
        }

        try {

            // try to change the directory
            if (!ftp.changeWorkingDirectory(getFtpPath())) {
                // if changing fails, make the directory
                if (!isFtpDirPreMade() && !ftp.makeDirectory(getFtpPath())) {
                    throw new DirectoryChangeFailedException();
                }

                // now change directory, if it fails again bail
                if (isCancelled()) {
                    return;
                }
                if (!ftp.changeWorkingDirectory(getFtpPath())) {
                    throw new DirectoryChangeFailedException();
                }
            }

            if (isCancelled()) {
                return;
            }
            connected();

            // upload xml files
            uploadFile(metaXmlName, new ByteArrayInputStream(metaXmlBytes), ftp);

            uploadFile(filesXmlName, new ByteArrayInputStream(filesXmlBytes), ftp);

            // now switch to binary mode
            if (isCancelled()) {
                return;
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);

            // upload contributed files
            for (final Iterator i = files.iterator(); i.hasNext();) {
                final File f = (File) i.next();

                uploadFile(f.getRemoteFileName(), new FileInputStream(f.getIOFile()), ftp);
            }
        } catch (InterruptedIOException ioe) {
            // we've been requested to cancel
            return;
        } finally {
            ftp.logout(); // we don't care if logging out fails
        }
    } finally {
        try {
            ftp.disconnect();
        } catch (IOException e) {
        } // don't care if disconnecting fails
    }

    // now tell the Internet Archive that we're done
    if (isCancelled()) {
        return;
    }
    checkinStarted();

    if (isCancelled()) {
        return;
    }
    checkin();

    if (isCancelled()) {
        return;
    }
    checkinCompleted();
}

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

/**
 * @see it.greenvulcano.util.remotefs.RemoteManager#connect(Map<String,
 *      String>)//w  ww.ja v a  2s  .c  o  m
 */
@SuppressWarnings("deprecation")
@Override
public void connect(Map<String, String> optProperties) throws RemoteManagerException {
    if (!isConnected) {
        int reply = 0;
        boolean errorsOccurred = true;
        String localHostname = hostname;
        try {
            Map<String, Object> localProps = MapUtils.convertToHMStringObject(optProperties);
            String localUsername = PropertiesHandler.expand(username, localProps);
            String localPassword = XMLConfig.getDecrypted(PropertiesHandler.expand(password, localProps));
            localHostname = PropertiesHandler.expand(hostname, localProps);

            logger.debug("Connecting to FTP server " + localHostname + ":" + port + "...");
            ftpClient.connect(localHostname, port);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                throw new RemoteManagerException("FTP server (" + getManagerKey(optProperties)
                        + ") refused connection: " + ftpClient.getReplyString());
            }
            logger.debug("FTP server reply: " + ftpClient.getReplyString().trim());

            //logger.debug("Logging in as FTP user " + localUsername + "/" + localPassword + "...");
            logger.debug("Logging in as FTP user " + localUsername + "...");
            ftpClient.login(localUsername, localPassword);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                throw new RemoteManagerException("FTP server (" + getManagerKey(optProperties)
                        + ") refused user login: " + ftpClient.getReplyString());
            }
            logger.debug("FTP server reply: " + ftpClient.getReplyString().trim());

            logger.debug("Entering local passive mode...");
            ftpClient.enterLocalPassiveMode();

            logger.debug(
                    "Connected to FTP server " + localHostname + " and logged in as FTP user " + localUsername);
            logger.debug("Current working directory is: " + ftpClient.printWorkingDirectory());
            logger.debug("FTP Server name is: " + ftpClient.getSystemName());
            isConnected = true;
            errorsOccurred = false;
        } catch (RemoteManagerException exc) {
            throw exc;
        } catch (SocketException exc) {
            throw new RemoteManagerException("Protocol error. " + getManagerKey(optProperties), exc);
        } catch (IOException exc) {
            throw new RemoteManagerException("I/O error. " + getManagerKey(optProperties), exc);
        } catch (Exception exc) {
            throw new RemoteManagerException("Generic error. " + getManagerKey(optProperties), exc);
        } finally {
            if (errorsOccurred) {
                if (ftpClient.isConnected()) {
                    try {
                        logger.debug("Disconnecting from FTP server " + localHostname + "...");
                        ftpClient.disconnect();
                    } catch (Exception exc) {
                        logger.warn("Disconnection from FTP server " + localHostname + " failed", exc);
                    }
                }
            }
        }
    }
}

From source file:net.sourceforge.dvb.projectx.xinput.ftp.FtpServer.java

public boolean test() {

    int base = 0;
    boolean error = false;
    FTPFile[] ftpFiles;//from  w w  w  .  j a  v a2s. com

    testMsg = null;

    try {
        int reply;
        ftpClient.connect(ftpVO.getServer(), ftpVO.getPortasInteger());

        // Check connection
        reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            testMsg = Resource.getString("ftpchooser.msg.noconnect");
            return false;
        }

        // Login
        if (!ftpClient.login(ftpVO.getUser(), ftpVO.getPassword())) {
            ftpClient.logout();
            testMsg = Resource.getString("ftpchooser.msg.nologin");
            return false;
        }

        ftpClient.syst();

        // Change directory
        if (!ftpClient.changeWorkingDirectory(ftpVO.getDirectory())) {
            testMsg = Resource.getString("ftpchooser.msg.nodirectory");
            return false;
        }

        testMsg = Resource.getString("ftpchooser.msg.success");
        ftpClient.logout();

    } catch (IOException ex) {
        testMsg = ex.getLocalizedMessage();
        error = true;
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException f) {
            }
        }
    }
    return !error;
}

From source file:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java

public FTPClient getFtpClient(HashMap<String, String> params) {
    String urlServer = params.get("urlServer");
    String usuario = params.get("user");
    String pass = params.get("pass");
    //        String workingDir = params.get("workingDir");

    FTPClient ret = null;/*from ww  w . j a va2  s  . co  m*/
    try {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(InetAddress.getByName(urlServer));
        ftpClient.login(usuario, pass);
        //Verificar conexin con el servidor.
        int reply = ftpClient.getReplyCode();
        System.out.println("Estatus de conexion FTP:" + reply);
        if (FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Conectado exitosamente");
        } else {
            System.out.println("No se pudo conectar con el servidor");
        }
        //directorio de trabajo
        //            ftpClient.changeWorkingDirectory(workingDir);
        System.out.println("Establecer carpeta de trabajo");
        //Activar que se envie cualquier tipo de archivo
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        ret = ftpClient;
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
    return ret;
}

From source file:net.audumla.climate.bom.BOMDataLoader.java

private synchronized FTPClient getFTPClient(String host) {
    FTPClient ftp = ftpClients.get(host);
    if (ftp == null || !ftp.isAvailable() || !ftp.isConnected()) {
        ftp = new FTPClient();
        FTPClientConfig config = new FTPClientConfig();
        ftp.configure(config);/*from  ww  w.j ava  2  s  . c o  m*/
        try {
            ftp.setControlKeepAliveTimeout(30);
            ftp.setControlKeepAliveReplyTimeout(5);
            ftp.setDataTimeout(3000);
            ftp.setDefaultTimeout(1000);
            int reply;
            ftp.connect(host);
            LOG.debug("Connected to " + host);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                LOG.error("FTP server '" + host + "' refused connection.");
            } else {
                if (!ftp.login("anonymous", "guest")) {
                    LOG.error("Unable to login to server " + host);
                }
                ftp.setSoTimeout(60000);
                ftp.enterLocalPassiveMode();
                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

            }
        } catch (IOException e) {
            LOG.error("Unable to connect to " + host, e);
        }
        ftpClients.put(host, ftp);
    }
    if (!ftp.isConnected() || !ftp.isAvailable()) {
        throw new UnsupportedOperationException("Cannot connect to " + host);
    }
    return ftp;
}

From source file:com.mirth.connect.connectors.file.filesystems.FtpConnection.java

@Override
public List<String> listDirectories(String fromDir) throws Exception {
    List<String> directories = new ArrayList<String>();

    if (!cwd(fromDir)) {
        logger.error(//from   w ww  .j  a v  a  2 s. c o  m
                "listFiles.changeWorkingDirectory: " + client.getReplyCode() + "-" + client.getReplyString());
        throw new IOException("Ftp error: " + client.getReplyCode());
    }

    FTPFile[] ftpDirectories = client.listDirectories();
    if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
        logger.error("listFiles.listFiles: " + client.getReplyCode() + "-" + client.getReplyString());
        throw new IOException("Ftp error: " + client.getReplyCode());
    }

    for (FTPFile directory : ftpDirectories) {
        if (directory != null) {
            directories.add(new FtpFileInfo(fromDir, directory).getAbsolutePath());
        }
    }

    return directories;
}