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

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

Introduction

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

Prototype

public int getReplyCode() 

Source Link

Document

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

Usage

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

public void receive(List<String> fileNames) {
    try {/* ww w  .  ja v a2s .c  o  m*/
        HashMap<String, String> params = getFtpParams();
        FTPClient ftpClient = getFtpClient(params);
        BufferedInputStream buffIn;
        ftpClient.enterLocalPassiveMode();
        for (String nombre : fileNames) {
            buffIn = new BufferedInputStream(ftpClient
                    .retrieveFileStream(params.get("remoteRetreiveFiles") + REMOTE_SEPARATOR + nombre));//Ruta completa de alojamiento en el FTP
            if (ftpClient.getReplyCode() == 150) {
                System.out.println("Archivo obtenido exitosamente");
                // write the inputStream to a FileOutputStream
                OutputStream outputStream = new FileOutputStream(
                        new File(params.get("localStoreFiles") + File.separator + nombre));
                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = buffIn.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                buffIn.close(); //Cerrar envio de arcivos al FTP
                outputStream.close();
            } else {
                System.out.println(
                        "No se pudo obtener el archivo: " + nombre + ", codigo:" + ftpClient.getReplyCode());
            }
        }

        ftpClient.logout(); //Cerrar sesin
        ftpClient.disconnect();//Desconectarse del servidor
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
}

From source file:com.eryansky.common.utils.ftp.FtpFactory.java

/**
 * FTP?./*from   w  ww . j a v a2  s.com*/
 * 
 * @param remotePath
 *            FTP?
 * @param fileName
 *            ???
 * @param localPath
 *            ??
 * @return
 */
public boolean ftpDownFile(String remotePath, String fileName, String localPath) {
    // ?
    boolean success = false;
    // FTPClient
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding("GBK");
    try {
        int reply;
        // FTP?
        // ??ftp.connect(url)?FTP?
        ftp.connect(url, port);
        // ftp
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        // 
        ftp.changeWorkingDirectory(remotePath);
        // 
        FTPFile[] fs = ftp.listFiles();
        // ??
        for (FTPFile ff : fs) {
            if (ff.getName().equals(fileName)) {
                // ???
                File localFile = new File(localPath + "/" + ff.getName());
                // ?
                OutputStream is = new FileOutputStream(localFile);
                // 
                ftp.retrieveFile(ff.getName(), is);
                is.close();
                success = true;
            }
        }
        ftp.logout();
        // ?

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}

From source file:com.cisco.dvbu.ps.utils.net.FtpFile.java

public void ftpFile(String fileName) throws CustomProcedureException, SQLException {

    // new ftp client
    FTPClient ftp = new FTPClient();
    OutputStream output = null;//  w ww  .  j a  v  a  2 s .  c  o m

    success = false;
    try {
        //try to connect
        ftp.connect(hostIp);

        //login to server
        if (!ftp.login(userId, userPass)) {
            ftp.logout();
            qenv.log(LOG_ERROR, "Ftp server refused connection user/password incorrect.");
        }
        int reply = ftp.getReplyCode();

        //FTPReply stores a set of constants for FTP Reply codes
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            qenv.log(LOG_ERROR, "Ftp server refused connection.");
        }

        //enter passive mode
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE, FTPClient.BINARY_FILE_TYPE);
        ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();

        //get system name
        //System.out.println("Remote system is " + ftp.getSystemType());

        //change current directory
        ftp.changeWorkingDirectory(ftpDirName);
        System.out.println("Current directory is " + ftp.printWorkingDirectory());
        System.out.println("File is " + fileName);

        output = new FileOutputStream(dirName + "/" + fileName);

        //get the file from the remote system
        success = ftp.retrieveFile(fileName, output);

        //close output stream
        output.close();

    } catch (IOException ex) {
        throw new CustomProcedureException("Error in CJP " + getName() + ": " + ex.toString());
    }
}

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

/**
 * API to download a particular directory from FTP Server.
 * //from  w ww . j  av a  2 s.  c  o 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:hd3gtv.storage.AbstractFileBridgeFtpNexio.java

private FTPClient connectMe() throws IOException {
    FTPClient ftpclient = new FTPClient();
    ftpclient.connect(configurator.host, configurator.port);

    if (ftpclient.login(configurator.username, configurator.password) == false) {
        ftpclient.logout();//  w ww .j ava2 s.  c  o m
        throw new IOException("Can't login to server");
    }
    int reply = ftpclient.getReplyCode();
    if (FTPReply.isPositiveCompletion(reply) == false) {
        ftpclient.disconnect();
        throw new IOException("Can't login to server");
    }

    ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

    if (configurator.passive) {
        ftpclient.enterLocalPassiveMode();
    } else {
        ftpclient.enterLocalActiveMode();
    }
    ftpclient.changeWorkingDirectory("/" + path);
    if (ftpclient.printWorkingDirectory().equals("/" + path) == false) {
        throw new IOException("Can't change working dir : " + "/" + path);
    }

    return ftpclient;
}

From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java

@Override
public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    // PluginConfig pluginConfig = getPluginConfig();
    // if (pluginConfig != null) {
    Map<String, String> ftpInfo = getFtpInfo("all");
    String urlPrefix = DataConfig.getConfig("IMGFTPROOT");
    FTPClient ftpClient = new FTPClient();
    try {/*w  ww  .j  a  v a2  s  .c om*/
        ftpClient.connect(ftpInfo.get("host"), 21);
        ftpClient.login(ftpInfo.get("username"), ftpInfo.get("password"));
        ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()) && ftpClient.changeWorkingDirectory(path)) {
            for (FTPFile ftpFile : ftpClient.listFiles()) {
                FileInfo fileInfo = new FileInfo();
                fileInfo.setName(ftpFile.getName());
                fileInfo.setUrl(urlPrefix + path + ftpFile.getName());
                fileInfo.setIsDirectory(ftpFile.isDirectory());
                fileInfo.setSize(ftpFile.getSize());
                fileInfo.setLastModified(ftpFile.getTimestamp().getTime());
                fileInfos.add(fileInfo);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
            }
        }
    }
    // }
    return fileInfos;
}

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

private boolean storeFTPFile(String host, String location, OutputStream os) {
    FTPClient ftp = getFTPClient(host);
    try {// w w  w .j a  v  a 2s .  c  o  m
        if (getFTPFile(host, location) != null) {
            synchronized (ftp) {
                IOUtils.copy(ftp.retrieveFileStream(location), os);
            }
        } else {
            return false;
        }
    } catch (IOException ex) {
        LOG.warn("Unable to load file " + location + " FTP Reply -> " + ftp.getReplyCode(), ex);
        return false;
    } finally {
        try {
            os.close();
        } catch (Exception ex) {
            LOG.error("Unknown error encountered storing file " + location, ex);
        }
    }
    LOG.info("Retrieved remote FTP content - " + "ftp://" + host + location);
    try {
        if (!ftp.completePendingCommand()) {
            ftp.logout();
            ftp.disconnect();
        }
    } catch (Exception ex) {
        LOG.error("Unknown error encountered storing file " + location, ex);
    }
    return true;
}

From source file:net.shopxx.plugin.ftpStorage.FtpStoragePlugin.java

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

From source file:biz.gabrys.lesscss.extended.compiler.source.FtpSource.java

private FTPClient connect() {
    final FTPClient connection = new FTPClient();
    try {//from   w w w  . j a  va  2s .c  o m
        connection.setAutodetectUTF8(true);
        connection.connect(url.getHost(), port);
        connection.enterLocalActiveMode();
        if (!connection.login("anonymous", "gabrys.biz Extended LessCSS Compiler")) {
            throw new SourceException(
                    String.format("Cannot login as anonymous user, reason %s", connection.getReplyString()));
        }
        if (!FTPReply.isPositiveCompletion(connection.getReplyCode())) {
            throw new SourceException(String.format("Cannot download source \"%s\", reason: %s", url,
                    connection.getReplyString()));
        }
        connection.enterLocalPassiveMode();
        connection.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (final IOException e) {
        disconnect(connection);
        throw new SourceException(e);
    }
    return connection;
}

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

public static void save(URL url, InputStream input, String encoding) throws IOException {
    //        System.out.println( "URLUtilities.save( "+url+", "+encoding+")");

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

    String protocol = url.getProtocol();

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

        client = new FTPClient();
        //               System.out.println( "Connecting ...");
        client.connect(host);/* w w w  . j a  v a  2  s .c om*/
        //               System.out.println( "Connected.");

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            //                  System.out.println( "Disconnecting...");

            client.disconnect();
            throw new IOException("FTP Server \"" + host + "\" refused connection.");
        }

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

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

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

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

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

        //               System.out.println( "Writing output ...");

        OutputStream output = client.storeFileStream(url.getFile());

        //             if( !FTPReply.isPositiveIntermediate( client.getReplyCode())) {
        //                 output.close();
        //                 client.disconnect();
        //                 throw new IOException( "Could not transfer file \""+url.getFile()+"\".");
        //             }

        InputStreamReader reader = new InputStreamReader(input, encoding);
        OutputStreamWriter writer = new OutputStreamWriter(output, encoding);

        int ch = reader.read();

        while (ch != -1) {
            writer.write(ch);
            ch = reader.read();
        }

        writer.flush();
        writer.close();
        output.close();

        // Must call completePendingCommand() to finish command.
        if (!client.completePendingCommand()) {
            client.disconnect();
            throw new IOException("Could not transfer file \"" + url.getFile() + "\".");
        } else {
            client.disconnect();
        }

    } else if (protocol.equals("http") || protocol.equals("https")) {
        WebdavResource webdav = createWebdavResource(toString(url), username, password);
        if (webdav != null) {
            webdav.putMethod(url.getPath(), input);
            webdav.close();
        } else {
            throw new IOException("Could not transfer file \"" + url.getFile() + "\".");
        }
    } else if (protocol.equals("file")) {
        FileOutputStream stream = new FileOutputStream(toFile(url));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding));

        InputStreamReader reader = new InputStreamReader(input, encoding);

        int ch = reader.read();

        while (ch != -1) {
            writer.write(ch);

            ch = reader.read();
        }

        writer.flush();
        writer.close();
    } else {
        throw new IOException("The \"" + protocol + "\" protocol is not supported.");
    }
}