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:org.apache.hadoop.fs.ftp.FTPFileSystem.java

/**
 * Connect to the FTP server using configuration parameters *
 * /*from  w w  w.ja va  2s  .com*/
 * @return An FTPClient instance
 * @throws IOException
 */
private FTPClient connect() throws IOException {
    FTPClient client = null;
    Configuration conf = getConf();
    String host = conf.get("fs.ftp.host");
    int port = conf.getInt("fs.ftp.host.port", FTP.DEFAULT_PORT);
    String user = conf.get("fs.ftp.user." + host);
    String password = conf.get("fs.ftp.password." + host);
    client = new FTPClient();
    client.connect(host, port);
    int reply = client.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        throw new IOException("Server - " + host + " refused connection on port - " + port);
    } else if (client.login(user, password)) {
        client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
        client.setFileType(FTP.BINARY_FILE_TYPE);
        client.setBufferSize(DEFAULT_BUFFER_SIZE);
    } else {
        throw new IOException("Login failed on server - " + host + ", port - " + port);
    }

    return client;
}

From source file:org.apache.hadoop.fs.ftp.FTPFileSystem.java

/**
 * Logout and disconnect the given FTPClient. *
 * /* www .  j  a va  2 s  .  c o m*/
 * @param client
 * @throws IOException
 */
private void disconnect(FTPClient client) throws IOException {
    if (client != null) {
        if (!client.isConnected()) {
            throw new FTPException("Client not connected");
        }
        boolean logoutSuccess = client.logout();
        client.disconnect();
        if (!logoutSuccess) {
            LOG.warn("Logout failed while disconnecting, error code - " + client.getReplyCode());
        }
    }
}

From source file:org.apache.hadoop.fs.ftp.FTPFileSystem.java

@Override
public FSDataInputStream open(Path file, int bufferSize) throws IOException {
    FTPClient client = connect();
    Path workDir = new Path(client.printWorkingDirectory());
    Path absolute = makeAbsolute(workDir, file);
    FileStatus fileStat = getFileStatus(client, absolute);
    if (fileStat.isDir()) {
        disconnect(client);/*ww  w . j  a  v  a 2s .c  om*/
        throw new IOException("Path " + file + " is a directory.");
    }
    client.allocate(bufferSize);
    Path parent = absolute.getParent();
    // Change to parent directory on the
    // server. Only then can we read the
    // file
    // on the server by opening up an InputStream. As a side effect the working
    // directory on the server is changed to the parent directory of the file.
    // The FTP client connection is closed when close() is called on the
    // FSDataInputStream.
    client.changeWorkingDirectory(parent.toUri().getPath());
    InputStream is = client.retrieveFileStream(file.getName());
    FSDataInputStream fis = new FSDataInputStream(new FTPInputStream(is, client, statistics));
    if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
        // The ftpClient is an inconsistent state. Must close the stream
        // which in turn will logout and disconnect from FTP server
        fis.close();
        throw new IOException("Unable to open file: " + file + ", Aborting");
    }
    return fis;
}

From source file:org.apache.hadoop.fs.ftp.FTPFileSystem.java

/**
 * A stream obtained via this call must be closed before using other APIs of
 * this class or else the invocation will block.
 *//*from   ww w. j ava  2  s . com*/
@Override
public FSDataOutputStream create(Path file, FsPermission permission, boolean overwrite, int bufferSize,
        short replication, long blockSize, Progressable progress) throws IOException {
    final FTPClient client = connect();
    Path workDir = new Path(client.printWorkingDirectory());
    Path absolute = makeAbsolute(workDir, file);
    if (exists(client, file)) {
        if (overwrite) {
            delete(client, file);
        } else {
            disconnect(client);
            throw new IOException("File already exists: " + file);
        }
    }
    Path parent = absolute.getParent();
    if (parent == null || !mkdirs(client, parent, FsPermission.getDefault())) {
        parent = (parent == null) ? new Path("/") : parent;
        disconnect(client);
        throw new IOException("create(): Mkdirs failed to create: " + parent);
    }
    client.allocate(bufferSize);
    // Change to parent directory on the server. Only then can we write to the
    // file on the server by opening up an OutputStream. As a side effect the
    // working directory on the server is changed to the parent directory of the
    // file. The FTP client connection is closed when close() is called on the
    // FSDataOutputStream.
    client.changeWorkingDirectory(parent.toUri().getPath());
    FSDataOutputStream fos = new FSDataOutputStream(client.storeFileStream(file.getName()), statistics) {
        @Override
        public void close() throws IOException {
            super.close();
            if (!client.isConnected()) {
                throw new FTPException("Client not connected");
            }
            boolean cmdCompleted = client.completePendingCommand();
            disconnect(client);
            if (!cmdCompleted) {
                throw new FTPException("Could not complete transfer, Reply Code - " + client.getReplyCode());
            }
        }
    };
    if (!FTPReply.isPositivePreliminary(client.getReplyCode())) {
        // The ftpClient is an inconsistent state. Must close the stream
        // which in turn will logout and disconnect from FTP server
        fos.close();
        throw new IOException("Unable to create file: " + file + ", Aborting");
    }
    return fos;
}

From source file:org.apache.jmeter.protocol.ftp.sampler.FTPSampler.java

@Override
public SampleResult sample(Entry e) {
    SampleResult res = new SampleResult();
    res.setSuccessful(false); // Assume failure
    String remote = getRemoteFilename();
    String local = getLocalFilename();
    boolean binaryTransfer = isBinaryMode();
    res.setSampleLabel(getName());//from  w w  w . ja v  a 2 s . c om
    final String label = getLabel();
    res.setSamplerData(label);
    try {
        res.setURL(new URL(label));
    } catch (MalformedURLException e1) {
        log.warn("Cannot set URL: " + e1.getLocalizedMessage());
    }
    InputStream input = null;
    OutputStream output = null;

    res.sampleStart();
    FTPClient ftp = new FTPClient();
    try {
        savedClient = ftp;
        final int port = getPortAsInt();
        if (port > 0) {
            ftp.connect(getServer(), port);
        } else {
            ftp.connect(getServer());
        }
        res.latencyEnd();
        int reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            if (ftp.login(getUsername(), getPassword())) {
                if (binaryTransfer) {
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                }
                ftp.enterLocalPassiveMode();// should probably come from the setup dialog
                boolean ftpOK = false;
                if (isUpload()) {
                    String contents = getLocalFileContents();
                    if (contents.length() > 0) {
                        byte[] bytes = contents.getBytes(); // TODO - charset?
                        input = new ByteArrayInputStream(bytes);
                        res.setBytes(bytes.length);
                    } else {
                        File infile = new File(local);
                        res.setBytes((int) infile.length());
                        input = new BufferedInputStream(new FileInputStream(infile));
                    }
                    ftpOK = ftp.storeFile(remote, input);
                } else {
                    final boolean saveResponse = isSaveResponse();
                    ByteArrayOutputStream baos = null; // No need to close this
                    OutputStream target = null; // No need to close this
                    if (saveResponse) {
                        baos = new ByteArrayOutputStream();
                        target = baos;
                    }
                    if (local.length() > 0) {
                        output = new FileOutputStream(local);
                        if (target == null) {
                            target = output;
                        } else {
                            target = new TeeOutputStream(output, baos);
                        }
                    }
                    if (target == null) {
                        target = new NullOutputStream();
                    }
                    input = ftp.retrieveFileStream(remote);
                    if (input == null) {// Could not access file or other error
                        res.setResponseCode(Integer.toString(ftp.getReplyCode()));
                        res.setResponseMessage(ftp.getReplyString());
                    } else {
                        long bytes = IOUtils.copy(input, target);
                        ftpOK = bytes > 0;
                        if (saveResponse && baos != null) {
                            res.setResponseData(baos.toByteArray());
                            if (!binaryTransfer) {
                                res.setDataType(SampleResult.TEXT);
                            }
                        } else {
                            res.setBytes((int) bytes);
                        }
                    }
                }

                if (ftpOK) {
                    res.setResponseCodeOK();
                    res.setResponseMessageOK();
                    res.setSuccessful(true);
                } else {
                    res.setResponseCode(Integer.toString(ftp.getReplyCode()));
                    res.setResponseMessage(ftp.getReplyString());
                }
            } else {
                res.setResponseCode(Integer.toString(ftp.getReplyCode()));
                res.setResponseMessage(ftp.getReplyString());
            }
        } else {
            res.setResponseCode("501"); // TODO
            res.setResponseMessage("Could not connect");
            //res.setResponseCode(Integer.toString(ftp.getReplyCode()));
            res.setResponseMessage(ftp.getReplyString());
        }
    } catch (IOException ex) {
        res.setResponseCode("000"); // TODO
        res.setResponseMessage(ex.toString());
    } finally {
        savedClient = null;
        if (ftp.isConnected()) {
            try {
                ftp.logout();
            } catch (IOException ignored) {
            }
            try {
                ftp.disconnect();
            } catch (IOException ignored) {
            }
        }
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
    }

    res.sampleEnd();
    return res;
}

From source file:org.apache.ofbiz.common.FtpServices.java

public static Map<String, Object> putFile(DispatchContext dctx, Map<String, ?> context) {
    Locale locale = (Locale) context.get("locale");
    Debug.logInfo("[putFile] starting...", module);
    InputStream localFile = null;
    try {// w  ww.j a  v  a 2s . co m
        localFile = new FileInputStream((String) context.get("localFilename"));
    } catch (IOException ioe) {
        Debug.logError(ioe, "[putFile] Problem opening local file", module);
        return ServiceUtil
                .returnError(UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale));
    }
    List<String> errorList = new LinkedList<String>();
    FTPClient ftp = new FTPClient();
    try {
        Integer defaultTimeout = (Integer) context.get("defaultTimeout");
        if (UtilValidate.isNotEmpty(defaultTimeout)) {
            Debug.logInfo("[putFile] set default timeout to: " + defaultTimeout.intValue() + " milliseconds",
                    module);
            ftp.setDefaultTimeout(defaultTimeout.intValue());
        }
        Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module);
        ftp.connect((String) context.get("hostname"));
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            Debug.logInfo("[putFile] Server refused connection", module);
            errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale));
        } else {
            String username = (String) context.get("username");
            String password = (String) context.get("password");
            Debug.logInfo("[putFile] logging in: username=" + username + ", password=" + password, module);
            if (!ftp.login(username, password)) {
                Debug.logInfo("[putFile] login failed", module);
                errorList.add(UtilProperties.getMessage(resource, "CommonFtpLoginFailure",
                        UtilMisc.toMap("username", username, "password", password), locale));
            } else {
                Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
                boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
                if (binary) {
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                }
                Boolean passiveMode = (Boolean) context.get("passiveMode");
                boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue();
                if (passive) {
                    ftp.enterLocalPassiveMode();
                }
                Debug.logInfo("[putFile] storing local file remotely as: " + context.get("remoteFilename"),
                        module);
                if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) {
                    Debug.logInfo("[putFile] store was unsuccessful", module);
                    errorList.add(UtilProperties.getMessage(resource, "CommonFtpFileNotSentSuccesfully",
                            UtilMisc.toMap("replyString", ftp.getReplyString()), locale));
                } else {
                    Debug.logInfo("[putFile] store was successful", module);
                    List<String> siteCommands = checkList(context.get("siteCommands"), String.class);
                    if (siteCommands != null) {
                        for (String command : siteCommands) {
                            Debug.logInfo("[putFile] sending SITE command: " + command, module);
                            if (!ftp.sendSiteCommand(command)) {
                                errorList.add(UtilProperties.getMessage(resource, "CommonFtpSiteCommandFailed",
                                        UtilMisc.toMap("command", command, "replyString", ftp.getReplyString()),
                                        locale));
                            }
                        }
                    }
                }
            }
            ftp.logout();
        }
    } catch (IOException ioe) {
        Debug.logWarning(ioe, "[putFile] caught exception: " + ioe.getMessage(), module);
        errorList.add(UtilProperties.getMessage(resource, "CommonFtpProblemWithTransfer",
                UtilMisc.toMap("errorString", ioe.getMessage()), locale));
    } finally {
        try {
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        } catch (Exception e) {
            Debug.logWarning(e, "[putFile] Problem with FTP disconnect: ", module);
        }
        try {
            localFile.close();
        } catch (Exception e) {
            Debug.logWarning(e, "[putFile] Problem closing local file: ", module);
        }
    }
    if (errorList.size() > 0) {
        Debug.logError("[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList,
                module);
        return ServiceUtil.returnError(errorList);
    }
    Debug.logInfo("[putFile] finished successfully", module);
    return ServiceUtil.returnSuccess();
}

From source file:org.apache.ofbiz.common.FtpServices.java

public static Map<String, Object> getFile(DispatchContext dctx, Map<String, ?> context) {
    Locale locale = (Locale) context.get("locale");
    String localFilename = (String) context.get("localFilename");
    OutputStream localFile = null;
    try {//  w ww.  j  ava 2  s  . co m
        localFile = new FileOutputStream(localFilename);
    } catch (IOException ioe) {
        Debug.logError(ioe, "[getFile] Problem opening local file", module);
        return ServiceUtil
                .returnError(UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale));
    }
    List<String> errorList = new LinkedList<String>();
    FTPClient ftp = new FTPClient();
    try {
        Integer defaultTimeout = (Integer) context.get("defaultTimeout");
        if (UtilValidate.isNotEmpty(defaultTimeout)) {
            Debug.logInfo("[getFile] Set default timeout to: " + defaultTimeout.intValue() + " milliseconds",
                    module);
            ftp.setDefaultTimeout(defaultTimeout.intValue());
        }
        ftp.connect((String) context.get("hostname"));
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale));
        } else {
            String username = (String) context.get("username");
            String password = (String) context.get("password");
            if (!ftp.login(username, password)) {
                errorList.add(UtilProperties.getMessage(resource, "CommonFtpLoginFailure",
                        UtilMisc.toMap("username", username, "password", password), locale));
            } else {
                Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
                boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
                if (binary) {
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                }
                Boolean passiveMode = (Boolean) context.get("passiveMode");
                boolean passive = (passiveMode == null) ? false : passiveMode.booleanValue();
                if (passive) {
                    ftp.enterLocalPassiveMode();
                }
                if (!ftp.retrieveFile((String) context.get("remoteFilename"), localFile)) {
                    errorList.add(UtilProperties.getMessage(resource, "CommonFtpFileNotSentSuccesfully",
                            UtilMisc.toMap("replyString", ftp.getReplyString()), locale));
                }
            }
            ftp.logout();
        }
    } catch (IOException ioe) {
        Debug.logWarning(ioe, "[getFile] caught exception: " + ioe.getMessage(), module);
        errorList.add(UtilProperties.getMessage(resource, "CommonFtpProblemWithTransfer",
                UtilMisc.toMap("errorString", ioe.getMessage()), locale));
    } finally {
        try {
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        } catch (Exception e) {
            Debug.logWarning(e, "[getFile] Problem with FTP disconnect: ", module);
        }
        try {
            localFile.close();
        } catch (Exception e) {
            Debug.logWarning(e, "[getFile] Problem closing local file: ", module);
        }
    }
    if (errorList.size() > 0) {
        Debug.logError("[getFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList,
                module);
        return ServiceUtil.returnError(errorList);
    }
    return ServiceUtil.returnSuccess();
}

From source file:org.apache.sqoop.connector.mainframe.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(TransferableContext context, LinkConfiguration linkConfiguration)
        throws IOException {
    FTPClient ftp = null;
    try {//w ww  .  j  av  a2s.com
        String username = linkConfiguration.linkConfig.username;
        String password;
        if (username == null) {
            username = "anonymous";
            password = "";
        } else {
            password = linkConfiguration.linkConfig.password;
        }

        String connectString = linkConfiguration.linkConfig.uri;
        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();
        }

        // The following section to get the system key for FTPClientConfig is just there for testing purposes
        String systemKey = null;
        String systemTypeString = context.getString("spark.mainframe.connector.system.type", "MVS");
        if (systemTypeString.equals("MVS")) {
            systemKey = FTPClientConfig.SYST_MVS;
        } else if (systemTypeString.equals("UNIX")) {
            systemKey = FTPClientConfig.SYST_UNIX;
        } else {
            assert (false);
        }

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

        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()));
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString());
        }
        // set ASCII transfer mode
        ftp.setFileType(FTP.ASCII_FILE_TYPE);
        // 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:org.apache.sqoop.util.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(Configuration conf) throws IOException {
    FTPClient ftp = null;
    try {/*from  w  ww .  j  a v a 2  s  .  c  o 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()));
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString());
        }
        // set ASCII transfer mode
        ftp.setFileType(FTP.ASCII_FILE_TYPE);
        // Use passive mode as default.
        ftp.enterLocalPassiveMode();
        LOG.info("System type detected: " + ftp.getSystemType());
    } 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:org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * auto find the time difference between local and remote
 * @param ftp handle to ftp client//from w w  w .j  a  va  2 s  .  c o  m
 * @return number of millis to add to remote time to make it comparable to local time
 * @since ant 1.6
 */
private long getTimeDiff(FTPClient ftp) {
    long returnValue = 0;
    File tempFile = findFileName(ftp);
    try {
        // create a local temporary file
        FILE_UTILS.createNewFile(tempFile);
        long localTimeStamp = tempFile.lastModified();
        BufferedInputStream instream = new BufferedInputStream(new FileInputStream(tempFile));
        ftp.storeFile(tempFile.getName(), instream);
        instream.close();
        boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());
        if (success) {
            FTPFile[] ftpFiles = ftp.listFiles(tempFile.getName());
            if (ftpFiles.length == 1) {
                long remoteTimeStamp = ftpFiles[0].getTimestamp().getTime().getTime();
                returnValue = localTimeStamp - remoteTimeStamp;
            }
            ftp.deleteFile(ftpFiles[0].getName());
        }
        // delegate the deletion of the local temp file to the delete task
        // because of race conditions occurring on Windows
        Delete mydelete = new Delete();
        mydelete.bindToOwner(this);
        mydelete.setFile(tempFile.getCanonicalFile());
        mydelete.execute();
    } catch (Exception e) {
        throw new BuildException(e, getLocation());
    }
    return returnValue;
}