Package org.apache.commons.net.ftp

Examples of org.apache.commons.net.ftp.FTPClient


    // Implementation methods
    //-------------------------------------------------------------------------


    protected void pollFileOrDirectory(String fileOrDirectory) throws Exception {
        FTPClient ftp = borrowClient();
        try {
            logger.debug("Polling directory " + fileOrDirectory);
            pollFileOrDirectory(ftp, fileOrDirectory, isRecursive());
        } finally {
            returnClient(ftp);
View Full Code Here


            }
        });
    }

    protected boolean processFileAndDelete(String file) {
        FTPClient ftp = null;
        boolean unlock = true;
        try {
            ftp = borrowClient();
            if (logger.isDebugEnabled()) {
                logger.debug("Processing file " + file);
            }
            if (ftp.listFiles(file).length > 0) {
                // Process the file. If processing fails, an exception should be thrown.
                processFile(ftp, file);
                // Processing is successful
                // We should not unlock until the file has been deleted
                unlock = false;
                if (isDeleteFile()) {
                    if (!ftp.deleteFile(file)) {
                        throw new IOException("Could not delete file " + file);
                    }
                    unlock = true;
                }
            } else {
View Full Code Here

    private String getWorkingPath() {
      return path == null ? "." : path;
    }

    public void poll() throws Exception {
        FTPClient ftp = (FTPClient) borrowClient();
        try {
            FTPFile[] files = ftp.listFiles(getWorkingPath());
            for (int i = 0; i < files.length; i++) {
                pollFile(files[i]);
            }
        }
        finally {
View Full Code Here

    protected void processFile(FTPFile file) {
        if (file.getName().equals(".") || file.getName().equals("..")) { // TODO: what about other directories?
          return;
        }
        FTPClient client = null;
        try {
            client = (FTPClient) borrowClient();
            processFile(client, file);
            if (!client.deleteFile(getWorkingPath() + file.getName())) {
                throw new IOException("Could not delete file " + file);
            }
        }
        catch (Exception e) {
            log.error("Failed to process file: " + file + ". Reason: " + e, e);
View Full Code Here

            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale));
        }

        List<String> errorList = FastList.newInstance();

        FTPClient ftp = new FTPClient();
        try {
            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.logInfo(ioe, "[putFile] caught exception: " + ioe.getMessage(), module);
            errorList.add(UtilProperties.getMessage(resource, "CommonFtpProblemWithTransfer", UtilMisc.toMap("errorString", ioe.getMessage()), locale));
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException dce) {
                    Debug.logWarning(dce, "[putFile] Problem with FTP disconnect", module);
                }
            }
        }
View Full Code Here

            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale));
        }

        List<String> errorList = FastList.newInstance();

        FTPClient ftp = new FTPClient();
        try {
            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) {
            errorList.add(UtilProperties.getMessage(resource, "CommonFtpProblemWithTransfer", UtilMisc.toMap("errorString", ioe.getMessage()), locale));
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException dce) {
                    Debug.logWarning(dce, "[getFile] Problem with FTP disconnect", module);
                }
            }
        }
View Full Code Here

        if (args.length == 4)
        {
            dir = args[3];
        }

        FTPClient client = new FTPClient();
        client.connect(host);
        int reply = client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply))
        {
            throw new IllegalArgumentException("cant connect: " + reply);
        }
        if (!client.login(user, pass))
        {
            throw new IllegalArgumentException("login failed");
        }
        client.enterLocalPassiveMode();

        OutputStream os = client.storeFileStream(dir + "/test.txt");
        if (os == null)
        {
            throw new IllegalStateException(client.getReplyString());
        }
        os.write("test".getBytes());
        os.close();
        client.completePendingCommand();

        if (dir != null)
        {
            if (!client.changeWorkingDirectory(dir))
            {
                throw new IllegalArgumentException("change dir to '" + dir + "' failed");
            }
        }

        System.err.println("System: " + client.getSystemName());

        FTPFile[] files = client.listFiles();
        for (int i = 0; i < files.length; i++)
        {
            FTPFile file = files[i];
            if (file == null)
            {
                System.err.println("#" + i + ": " + null);
            }
            else
            {
                System.err.println("#" + i + ": " + file.getRawListing());
                System.err.println("#" + i + ": " + file.toString());
                System.err.println("\t name:" + file.getName() + " type:" + file.getType());
            }
        }
        client.disconnect();
    }
View Full Code Here

        }
    }
   
    public RemoteFileOperations<FTPFile> createRemoteFileOperations() throws Exception {
        // configure ftp client
        FTPClient client = ftpClient;
       
        if (client == null) {
            // must use a new client if not explicit configured to use a custom client
            client = createFtpClient();
        }

        // set any endpoint configured timeouts
        if (getConfiguration().getConnectTimeout() > -1) {
            client.setConnectTimeout(getConfiguration().getConnectTimeout());
        }
        if (getConfiguration().getSoTimeout() > -1) {
            soTimeout = getConfiguration().getSoTimeout();
        }
        dataTimeout = getConfiguration().getTimeout();

        // then lookup ftp client parameters and set those
        if (ftpClientParameters != null) {
            // setting soTimeout has to be done later on FTPClient (after it has connected)
            Object timeout = ftpClientParameters.remove("soTimeout");
            if (timeout != null) {
                soTimeout = getCamelContext().getTypeConverter().convertTo(int.class, timeout);
            }
            // and we want to keep data timeout so we can log it later
            timeout = ftpClientParameters.remove("dataTimeout");
            if (timeout != null) {
                dataTimeout = getCamelContext().getTypeConverter().convertTo(int.class, dataTimeout);
            }
            IntrospectionSupport.setProperties(client, ftpClientParameters);
        }
       
        if (ftpClientConfigParameters != null) {
            // client config is optional so create a new one if we have parameter for it
            if (ftpClientConfig == null) {
                ftpClientConfig = new FTPClientConfig();
            }
            IntrospectionSupport.setProperties(ftpClientConfig, ftpClientConfigParameters);
        }

        if (dataTimeout > 0) {
            client.setDataTimeout(dataTimeout);
        }

        if (log.isDebugEnabled()) {
            log.debug("Created FTPClient [connectTimeout: {}, soTimeout: {}, dataTimeout: {}]: {}",
                    new Object[]{client.getConnectTimeout(), getSoTimeout(), dataTimeout, client});
        }

        FtpOperations operations = new FtpOperations(client, getFtpClientConfig());
        operations.setEndpoint(this);
        return operations;
View Full Code Here

        operations.setEndpoint(this);
        return operations;
    }

    protected FTPClient createFtpClient() throws Exception {
        return new FTPClient();
    }
View Full Code Here

     *         correctly.
     */
    public void execute() throws BuildException {
        checkAttributes();

        FTPClient ftp = null;

        try {
            log("Opening FTP connection to " + server, Project.MSG_VERBOSE);

            ftp = new FTPClient();
            if (this.isConfigurationSet) {
                ftp = FTPConfigurator.configure(ftp, this);
            }

            ftp.connect(server, port);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("FTP connection failed: "
                     + ftp.getReplyString());
            }

            log("connected", Project.MSG_VERBOSE);
            log("logging in to FTP server", Project.MSG_VERBOSE);

            if ((this.account != null && !ftp.login(userid, password, account))
                    || (this.account == null && !ftp.login(userid, password))) {
                throw new BuildException("Could not login to FTP server");
            }

            log("login succeeded", Project.MSG_VERBOSE);

            if (binary) {
                ftp.setFileType(org.apache.commons.net.ftp.FTP.IMAGE_FILE_TYPE);
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    throw new BuildException("could not set transfer type: "
                        + ftp.getReplyString());
                }
            } else {
                ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE);
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    throw new BuildException("could not set transfer type: "
                        + ftp.getReplyString());
                }
            }

            if (passive) {
                log("entering passive mode", Project.MSG_VERBOSE);
                ftp.enterLocalPassiveMode();
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    throw new BuildException("could not enter into passive "
                         + "mode: " + ftp.getReplyString());
                }
            }

            // If an initial command was configured then send it.
            // Some FTP servers offer different modes of operation,
            // E.G. switching between a UNIX file system mode and
            // a legacy file system.
            if (this.initialSiteCommand != null) {
                RetryHandler h = new RetryHandler(this.retriesAllowed, this);
                final FTPClient lftp = ftp;
                executeRetryable(h, new Retryable() {
                    public void execute() throws IOException {
                        doSiteCommand(lftp, FTP.this.initialSiteCommand);
                    }
                }, "initial site command: " + this.initialSiteCommand);
            }


            // For a unix ftp server you can set the default mask for all files
            // created.

            if (umask != null) {
                RetryHandler h = new RetryHandler(this.retriesAllowed, this);
                final FTPClient lftp = ftp;
                executeRetryable(h, new Retryable() {
                    public void execute() throws IOException {
                        doSiteCommand(lftp, "umask " + umask);
                    }
                }, "umask " + umask);
            }

            // If the action is MK_DIR, then the specified remote
            // directory is the directory to create.

            if (action == MK_DIR) {
                RetryHandler h = new RetryHandler(this.retriesAllowed, this);
                final FTPClient lftp = ftp;
                executeRetryable(h, new Retryable() {
                    public void execute() throws IOException {
                        makeRemoteDir(lftp, remotedir);
                    }
                }, remotedir);
            } else if (action == SITE_CMD) {
                    RetryHandler h = new RetryHandler(this.retriesAllowed, this);
                    final FTPClient lftp = ftp;
                    executeRetryable(h, new Retryable() {
                        public void execute() throws IOException {
                            doSiteCommand(lftp, FTP.this.siteCommand);
                        }
                    }, "Site Command: " + this.siteCommand);
View Full Code Here

TOP

Related Classes of org.apache.commons.net.ftp.FTPClient

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.