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

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

Introduction

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

Prototype

public String getReplyString() 

Source Link

Document

Returns the entire text of the last FTP server response exactly as it was received, including all end of line markers in NETASCII format.

Usage

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

@Override
public void rename(final String source, final String target) throws IOException {
    final FTPClient client = getClient(null);
    final boolean renameSuccessful = client.rename(source, target);
    if (!renameSuccessful) {
        throw new IOException("Failed to rename temporary file " + source + " to " + target + " due to: "
                + client.getReplyString());
    }/*from ww w  .  j  a  va2 s . c o m*/
}

From source file:co.cask.hydrator.action.ftp.FTPCopyAction.java

@Override
public void run(ActionContext context) throws Exception {
    Path destination = new Path(config.getDestDirectory());
    FileSystem fileSystem = FileSystem.get(new Configuration());
    destination = fileSystem.makeQualified(destination);
    if (!fileSystem.exists(destination)) {
        fileSystem.mkdirs(destination);/*ww  w  . j av a 2  s.c o m*/
    }

    FTPClient ftp;
    if ("ftp".equals(config.getProtocol().toLowerCase())) {
        ftp = new FTPClient();
    } else {
        ftp = new FTPSClient();
    }
    ftp.setControlKeepAliveTimeout(5);
    // UNIX type server
    FTPClientConfig ftpConfig = new FTPClientConfig();
    // Set additional parameters required for the ftp
    // for example config.setServerTimeZoneId("Pacific/Pitcairn")
    ftp.configure(ftpConfig);
    try {
        ftp.connect(config.getHost(), config.getPort());
        ftp.enterLocalPassiveMode();
        String replyString = ftp.getReplyString();
        LOG.info("Connected to server {} and port {} with reply from connect as {}.", config.getHost(),
                config.getPort(), replyString);

        // Check the reply code for actual success
        int replyCode = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftp.disconnect();
            throw new RuntimeException(String.format("FTP server refused connection with code %s and reply %s.",
                    replyCode, replyString));
        }

        if (!ftp.login(config.getUserName(), config.getPassword())) {
            LOG.error("login command reply code {}, {}", ftp.getReplyCode(), ftp.getReplyString());
            ftp.logout();
            throw new RuntimeException(String.format(
                    "Login to the FTP server %s and port %s failed. " + "Please check user name and password.",
                    config.getHost(), config.getPort()));
        }

        FTPFile[] ftpFiles = ftp.listFiles(config.getSrcDirectory());
        LOG.info("listFiles command reply code: {}, {}.", ftp.getReplyCode(), ftp.getReplyString());
        // Check the reply code for listFiles call.
        // If its "522 Data connections must be encrypted" then it means data channel also need to be encrypted
        if (ftp.getReplyCode() == 522 && "sftp".equalsIgnoreCase(config.getProtocol())) {
            // encrypt data channel and listFiles again
            ((FTPSClient) ftp).execPROT("P");
            LOG.info("Attempting command listFiles on encrypted data channel.");
            ftpFiles = ftp.listFiles(config.getSrcDirectory());
        }
        for (FTPFile file : ftpFiles) {
            String source = config.getSrcDirectory() + "/" + file.getName();

            LOG.info("Current file {}, source {}", file.getName(), source);
            if (config.getExtractZipFiles() && file.getName().endsWith(".zip")) {
                copyZip(ftp, source, fileSystem, destination);
            } else {
                Path destinationPath = fileSystem.makeQualified(new Path(destination, file.getName()));
                LOG.debug("Downloading {} to {}", file.getName(), destinationPath.toString());
                try (OutputStream output = fileSystem.create(destinationPath)) {
                    InputStream is = ftp.retrieveFileStream(source);
                    ByteStreams.copy(is, output);
                }
            }
            if (!ftp.completePendingCommand()) {
                LOG.error("Error completing command.");
            }
        }
        ftp.logout();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (Throwable e) {
                LOG.error("Failure to disconnect the ftp connection.", e);
            }
        }
    }
}

From source file:com.wheelermarine.android.publicAccesses.Updater.java

@Override
protected Integer doInBackground(URL... urls) {

    try {/*from   w ww.ja va 2 s . c  o m*/
        final DatabaseHelper db = new DatabaseHelper(context);

        SQLiteDatabase database = db.getWritableDatabase();
        if (database == null)
            throw new IllegalStateException("Unable to open database!");

        database.beginTransaction();
        try {
            // Clear out the old data.
            database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null);

            // Connect to the web server and locate the FTP download link.
            Log.v(TAG, "Finding update: " + urls[0]);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Locating update...");
                    progress.setIndeterminate(true);
                }
            });
            Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get();
            URL dataURL = null;
            for (Element element : doc.select("a")) {
                if (element.hasAttr("href") && element.attr("href").startsWith("ftp://ftp.dnr.state.mn.us")) {
                    dataURL = new URL(element.attr("href"));
                }
            }

            // Make sure the download URL was fund.
            if (dataURL == null)
                throw new FileNotFoundException("Unable to locate data URL.");

            // Connect to the FTP server and download the update.
            Log.v(TAG, "Downloading update: " + dataURL);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Downloading update...");
                    progress.setIndeterminate(true);
                }
            });
            FTPClient ftp = new FTPClient();
            try {
                ftp.setConnectTimeout(timeout * 1000);
                ftp.setDefaultTimeout(timeout * 1000);
                ftp.connect(dataURL.getHost());
                ftp.enterLocalPassiveMode();

                // After connection attempt, you should check the reply code
                // to verify success.
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    ftp.disconnect();
                    throw new IOException("FTP server refused connection: " + ftp.getReplyString());
                }

                // Login using the standard anonymous credentials.
                if (!ftp.login("anonymous", "anonymous")) {
                    ftp.disconnect();
                    throw new IOException("FTP Error: " + ftp.getReplyString());
                }

                Map<Integer, Location> locations = null;

                // Download the ZIP archive.
                Log.v(TAG, "Downloading: " + dataURL.getFile());
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                InputStream in = ftp.retrieveFileStream(dataURL.getFile());
                if (in == null)
                    throw new FileNotFoundException(dataURL.getFile() + " was not found!");
                try {
                    ZipInputStream zin = new ZipInputStream(in);
                    try {
                        // Locate the .dbf entry in the ZIP archive.
                        ZipEntry entry;
                        while ((entry = zin.getNextEntry()) != null) {
                            if (entry.getName().endsWith(entryName)) {
                                readDBaseFile(zin, database);
                            } else if (entry.getName().endsWith(shapeEntryName)) {
                                locations = readShapeFile(zin);
                            }
                        }
                    } finally {
                        try {
                            zin.close();
                        } catch (Exception e) {
                            // Ignore this error.
                        }
                    }
                } finally {
                    in.close();
                }

                if (locations != null) {
                    final int recordCount = locations.size();
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progress.setIndeterminate(false);
                            progress.setMessage("Updating locations...");
                            progress.setMax(recordCount);
                        }
                    });

                    int progress = 0;
                    for (int recordNumber : locations.keySet()) {
                        PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber);
                        Location loc = locations.get(recordNumber);
                        access.setLatitude(loc.getLatitude());
                        access.setLongitude(loc.getLongitude());
                        db.updatePublicAccess(access);
                        publishProgress(++progress);
                    }
                }
            } finally {
                if (ftp.isConnected())
                    ftp.disconnect();
            }
            database.setTransactionSuccessful();
            return db.getPublicAccessesCount();
        } finally {
            database.endTransaction();
        }
    } catch (Exception e) {
        error = e;
        Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e);
        return -1;
    }
}

From source file:com.savy3.util.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(Configuration conf) throws IOException {
    FTPClient ftp = null;
    try {//from  www.  j  a v a 2  s .  co m
        String username = conf.get(DBConfiguration.USERNAME_PROPERTY);
        String password;
        if (username == null) {
            username = "anonymous";
            password = "";
        } else {
            password = DBConfiguration.getPassword((JobConf) conf);
        }
        String connectString = conf.get(DBConfiguration.URL_PROPERTY);
        String server = connectString;
        int port = 0;
        String[] parts = connectString.split(":");
        if (parts.length == 2) {
            server = parts[0];
            try {
                port = Integer.parseInt(parts[1]);
            } catch (NumberFormatException e) {
                LOG.warn("Invalid port number: " + e.toString());
            }
        }
        if (null != mockFTPClient) {
            ftp = mockFTPClient;
        } else {
            ftp = new FTPClient();
        }

        FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_MVS);
        ftp.configure(config);

        if (conf.getBoolean(JobBase.PROPERTY_VERBOSE, false)) {
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
        }
        try {
            if (port > 0) {
                ftp.connect(server, port);
            } else {
                ftp.connect(server);
            }
        } catch (IOException ioexp) {
            throw new IOException("Could not connect to server " + server, ioexp);
        }

        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString());
        }
        LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString());
        }
        // set Binary transfer mode
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.featureValue("LITERAL SITE RDW");
        ftp.doCommand("SITE", "RDW");
        System.out.println("reply for LITERAL" + ftp.getReplyString());
        // Use passive mode as default.
        ftp.enterLocalPassiveMode();
    } catch (IOException ioe) {
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        ftp = null;
        throw ioe;
    }
    return ftp;
}

From source file:it.zero11.acme.example.FTPChallengeListener.java

private boolean createChallengeFiles(String token, String challengeBody) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {//from   w w w  .j a  v  a  2  s.  c o m
        ftp.connect(host);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            return false;
        }

        ftp.login(username, password);
        ftp.changeWorkingDirectory(webroot);
        ftp.makeDirectory(".well-known");
        ftp.changeWorkingDirectory(".well-known");
        ftp.makeDirectory("acme-challenge");
        ftp.changeWorkingDirectory("acme-challenge");
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE, FTPClient.BINARY_FILE_TYPE);
        ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        success = ftp.storeFile(token, new ByteArrayInputStream(challengeBody.getBytes()));
        if (!success)
            System.err.println("FTP error uploading file: " + ftp.getReplyCode() + ": " + ftp.getReplyString());
        ftp.logout();
    } catch (IOException e) {
        throw new AcmeException(e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }

    return success;
}

From source file:ca.rmen.android.networkmonitor.app.speedtest.SpeedTestUpload.java

public static SpeedTestResult upload(SpeedTestUploadConfig uploadConfig) {
    Log.v(TAG, "upload " + uploadConfig);
    // Make sure we have a file to upload
    if (!uploadConfig.file.exists())
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);

    FTPClient ftp = new FTPClient();
    // For debugging, we'll log all the ftp commands
    if (BuildConfig.DEBUG) {
        PrintCommandListener printCommandListener = new PrintCommandListener(System.out);
        ftp.addProtocolCommandListener(printCommandListener);
    }//from www  .j a  v a 2s.  co m
    InputStream is = null;
    try {
        // Set buffer size of FTP client
        ftp.setBufferSize(1048576);
        // Open a connection to the FTP server
        ftp.connect(uploadConfig.server, uploadConfig.port);
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }
        // Login to the FTP server
        if (!ftp.login(uploadConfig.user, uploadConfig.password)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.AUTH_FAILURE);
        }
        // Try to change directories
        if (!TextUtils.isEmpty(uploadConfig.path) && !ftp.changeWorkingDirectory(uploadConfig.path)) {
            Log.v(TAG, "Upload: could not change path to " + uploadConfig.path);
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);
        }

        // set the file type to be read as a binary file
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        // Upload the file
        is = new FileInputStream(uploadConfig.file);
        long before = System.currentTimeMillis();
        long txBytesBefore = TrafficStats.getTotalTxBytes();
        if (!ftp.storeFile(uploadConfig.file.getName(), is)) {
            ftp.disconnect();
            Log.v(TAG, "Upload: could not store file to " + uploadConfig.path + ". Error code: "
                    + ftp.getReplyCode() + ", error string: " + ftp.getReplyString());
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }

        // Calculate stats
        long after = System.currentTimeMillis();
        long txBytesAfter = TrafficStats.getTotalTxBytes();
        ftp.logout();
        ftp.disconnect();
        Log.v(TAG, "Upload complete");
        return new SpeedTestResult(txBytesAfter - txBytesBefore, uploadConfig.file.length(), after - before,
                SpeedTestStatus.SUCCESS);
    } catch (SocketException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } catch (IOException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } finally {
        IoUtil.closeSilently(is);
    }
}

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

public void sendCommands(final List<String> commands, final FlowFile flowFile) throws IOException {
    if (commands.isEmpty()) {
        return;// w  w  w  .j  a  v  a2 s  .c  om
    }

    final FTPClient client = getClient(flowFile);
    for (String cmd : commands) {
        if (!cmd.isEmpty()) {
            int result;
            result = client.sendCommand(cmd);
            logger.debug(this + " sent command to the FTP server: " + cmd + " for " + flowFile);

            if (FTPReply.isNegativePermanent(result) || FTPReply.isNegativeTransient(result)) {
                throw new IOException(this + " negative reply back from FTP server cmd: " + cmd + " reply:"
                        + result + ": " + client.getReplyString() + " for " + flowFile);
            }
        }
    }
}

From source file:edu.wisc.ssec.mcidasv.data.cyclone.AtcfStormDataSource.java

/**
 * _more_//  www . j  a v a 2 s.  c  om
 * 
 * @param file
 *            _more_
 * @param ignoreErrors
 *            _more_
 * 
 * @return _more_
 * 
 * @throws Exception
 *             _more_
 */
private byte[] readFile(String file, boolean ignoreErrors) throws Exception {
    if (new File(file).exists()) {
        return IOUtil.readBytes(IOUtil.getInputStream(file, getClass()));
    }
    if (!file.startsWith("ftp:")) {
        if (ignoreErrors) {
            return null;
        }
        throw new FileNotFoundException("Could not read file: " + file);
    }

    URL url = new URL(file);
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(url.getHost());
        ftp.login("anonymous", "password");
        ftp.setFileType(FTP.IMAGE_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        if (ftp.retrieveFile(url.getPath(), bos)) {
            return bos.toByteArray();
        } else {
            throw new IOException("Unable to retrieve file:" + url);
        }
    } catch (org.apache.commons.net.ftp.FTPConnectionClosedException fcce) {
        System.err.println("ftp error:" + fcce);
        System.err.println(ftp.getReplyString());
        if (!ignoreErrors) {
            throw fcce;
        }
        return null;
    } catch (Exception exc) {
        if (!ignoreErrors) {
            throw exc;
        }
        return null;
    } finally {
        try {
            ftp.logout();
        } catch (Exception exc) {
        }
        try {
            ftp.disconnect();
        } catch (Exception exc) {
        }

    }
}

From source file:lucee.runtime.tag.Ftp.java

/**
 * writes cfftp variable/*from   w w  w. ja v a  2  s.c o m*/
 * @param client
 * @return FTPCLient
 * @throws PageException 
 */
private Struct writeCfftp(FTPClient client) throws PageException {
    Struct cfftp = new StructImpl();
    if (result == null)
        pageContext.variablesScope().setEL(CFFTP, cfftp);
    else
        pageContext.setVariable(result, cfftp);
    if (client == null) {
        cfftp.setEL(SUCCEEDED, Boolean.FALSE);
        cfftp.setEL(ERROR_CODE, new Double(-1));
        cfftp.setEL(ERROR_TEXT, "");
        cfftp.setEL(RETURN_VALUE, "");
        return cfftp;
    }
    int repCode = client.getReplyCode();
    String repStr = client.getReplyString();
    cfftp.setEL(ERROR_CODE, new Double(repCode));
    cfftp.setEL(ERROR_TEXT, repStr);

    cfftp.setEL(SUCCEEDED, Caster.toBoolean(FTPReply.isPositiveCompletion(repCode)));
    cfftp.setEL(RETURN_VALUE, repStr);
    return cfftp;
}

From source file:com.bdaum.zoom.net.core.ftp.FtpAccount.java

/**
 * Login into a account//from  ww w .j av a  2 s.  co  m
 *
 * @return FTPClient object or null
 * @throws IOException
 */
public FTPClient login() throws IOException {
    int reply = 0;
    FTPClient ftp = new FTPClient();
    try {
        if (port != 0)
            ftp.connect(getHost(), getPort());
        else
            ftp.connect(getHost());
        if (isAnonymous())
            ftp.login(ANONYMOUS, GUEST);
        else if (getSubAccount() != null && !getSubAccount().isEmpty())
            ftp.login(getLogin(), getPassword(), getSubAccount());
        else
            ftp.login(getLogin(), getPassword());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply))
            throw new IOException(NLS.bind(Messages.FtpAccount_ftp_server_refused, ftp.getReplyString()));
        if (isPassiveMode())
            ftp.enterLocalPassiveMode();
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
        throw e;
    }
    return ftp;
}