Package org.apache.commons.net.ftp

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


   * @see #closeFtpConnection()
   */
  public void openFtpConnection(String workingDirectory) throws RQLException {
    try {
      // create a client
      ftpClient = new FTPClient();
      ftpClient.connect(server);
      ftpClient.login(user, password);
      // change into rd import directory
      ftpClient.changeWorkingDirectory(workingDirectory);
    } catch (IOException ioex) {
View Full Code Here


            throw new AuthenticationException( "Password not specified for repository " + getRepository().getId() );
        }

        String host = getRepository().getHost();

        ftp = new FTPClient();
        ftp.setDefaultTimeout( getTimeout() );
        ftp.setDataTimeout( getTimeout() );
        ftp.setControlEncoding( getControlEncoding() );

        ftp.addProtocolCommandListener( new PrintCommandListener( this ) );
View Full Code Here

            password = "anonymous".toCharArray();
        }

        try
        {
            final FTPClient client = new FTPClient();

            configureClient(fileSystemOptions, client);

            FTPFileEntryParserFactory myFactory =
                FtpFileSystemConfigBuilder.getInstance().getEntryParserFactory(fileSystemOptions);
            if (myFactory != null)
            {
                client.setParserFactory(myFactory);
            }

            try
            {
                client.connect(hostname, port);

                int reply = client.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply))
                {
                    throw new FileSystemException("vfs.provider.ftp/connect-rejected.error", hostname);
                }

                // Login
                if (!client.login(
                    UserAuthenticatorUtils.toString(username),
                    UserAuthenticatorUtils.toString(password)))
                {
                    throw new FileSystemException("vfs.provider.ftp/login.error",
                        new Object[]{hostname, UserAuthenticatorUtils.toString(username)}, null);
                }

                // Set binary mode
                if (!client.setFileType(FTP.BINARY_FILE_TYPE))
                {
                    throw new FileSystemException("vfs.provider.ftp/set-binary.error", hostname);
                }

                // Set dataTimeout value
                Integer dataTimeout = FtpFileSystemConfigBuilder.getInstance().getDataTimeout(fileSystemOptions);
                if (dataTimeout != null)
                {
                    client.setDataTimeout(dataTimeout.intValue());
                }

                Integer socketTimeout = FtpFileSystemConfigBuilder.getInstance().getSoTimeout(fileSystemOptions);
                if (socketTimeout != null)
                {
                    client.setSoTimeout(socketTimeout.intValue());
                }

                // Change to root by default
                // All file operations a relative to the filesystem-root
                // String root = getRoot().getName().getPath();

                Boolean userDirIsRoot = FtpFileSystemConfigBuilder.getInstance().getUserDirIsRoot(fileSystemOptions);
                if (workingDirectory != null && (userDirIsRoot == null || !userDirIsRoot.booleanValue()))
                {
                    if (!client.changeWorkingDirectory(workingDirectory))
                    {
                        throw new FileSystemException("vfs.provider.ftp/change-work-directory.error", workingDirectory);
                    }
                }

                Boolean passiveMode = FtpFileSystemConfigBuilder.getInstance().getPassiveMode(fileSystemOptions);
                if (passiveMode != null && passiveMode.booleanValue())
                {
                    client.enterLocalPassiveMode();
                }

                String controlEncoding = FtpFileSystemConfigBuilder.getInstance().getControlEncoding(fileSystemOptions);
                if (controlEncoding != null)
                {
                    client.setControlEncoding(controlEncoding);
                }
            }
            catch (final IOException e)
            {
                if (client.isConnected())
                {
                    client.disconnect();
                }
                throw e;
            }

            return client;
View Full Code Here

    public InputStream retrieveFileStream(String relPath, long restartOffset) throws IOException
    {
        try
        {
            FTPClient client = getFtpClient();
            client.setRestartOffset(restartOffset);
            return client.retrieveFileStream(relPath);
        }
        catch (IOException e)
        {
            disconnect();

            FTPClient client = getFtpClient();
            client.setRestartOffset(restartOffset);
            return client.retrieveFileStream(relPath);
        }
    }
View Full Code Here

        }
    }
   
    protected 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: " + client.getConnectTimeout() + ", soTimeout: " + getSoTimeout() + ", dataTimeout: " + 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

    /**
     * Creates a new FtpClient
     */
    public CommonsNetFtpClient() {
        super("ftp");
        ftp = new FTPClient();
    }
View Full Code Here

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

        FTPClient ftp = null;

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

            ftp = new FTPClient();

            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 (!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());
                }
            }

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

            if (umask != null) {
                doSiteCommand(ftp, "umask " + umask);
            }

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

            if (action == MK_DIR) {
                makeRemoteDir(ftp, remotedir);
            } else {
                if (remotedir != null) {
                    log("changing the remote directory", Project.MSG_VERBOSE);
                    ftp.changeWorkingDirectory(remotedir);
                    if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        throw new BuildException("could not change remote "
                             + "directory: " + ftp.getReplyString());
                    }
                }
                if (newerOnly && timeDiffAuto) {
                // in this case we want to find how much time span there is between local
                // and remote
                    timeDiffMillis = getTimeDiff(ftp);
                }
                log(ACTION_STRS[action] + " " + ACTION_TARGET_STRS[action]);
                transferFiles(ftp);
            }

        } catch (IOException ex) {
            throw new BuildException("error during FTP transfer: " + ex);
        } finally {
            if (ftp != null && ftp.isConnected()) {
                try {
                    log("disconnecting", Project.MSG_VERBOSE);
                    ftp.logout();
                    ftp.disconnect();
                } catch (IOException ex) {
                    // ignore it
                }
            }
        }
View Full Code Here

    public static final void main(String[] args)
    {
        String server1, username1, password1, file1;
        String server2, username2, password2, file2;
        FTPClient ftp1, ftp2;
        ProtocolCommandListener listener;

        if (args.length < 8)
        {
            System.err.println(
                "Usage: ftp <host1> <user1> <pass1> <file1> <host2> <user2> <pass2> <file2>"
            );
            System.exit(1);
        }

        server1 = args[0];
        username1 = args[1];
        password1 = args[2];
        file1 = args[3];
        server2 = args[4];
        username2 = args[5];
        password2 = args[6];
        file2 = args[7];

        listener = new PrintCommandListener(new PrintWriter(System.out));
        ftp1 = new FTPClient();
        ftp1.addProtocolCommandListener(listener);
        ftp2 = new FTPClient();
        ftp2.addProtocolCommandListener(listener);

        try
        {
            int reply;
            ftp1.connect(server1);
            System.out.println("Connected to " + server1 + ".");

            reply = ftp1.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp1.disconnect();
                System.err.println("FTP server1 refused connection.");
                System.exit(1);
            }
        }
        catch (IOException e)
        {
            if (ftp1.isConnected())
            {
                try
                {
                    ftp1.disconnect();
                }
                catch (IOException f)
                {
                    // do nothing
                }
            }
            System.err.println("Could not connect to server1.");
            e.printStackTrace();
            System.exit(1);
        }

        try
        {
            int reply;
            ftp2.connect(server2);
            System.out.println("Connected to " + server2 + ".");

            reply = ftp2.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp2.disconnect();
                System.err.println("FTP server2 refused connection.");
                System.exit(1);
            }
        }
        catch (IOException e)
        {
            if (ftp2.isConnected())
            {
                try
                {
                    ftp2.disconnect();
                }
                catch (IOException f)
                {
                    // do nothing
                }
            }
            System.err.println("Could not connect to server2.");
            e.printStackTrace();
            System.exit(1);
        }

__main:
        try
        {
            if (!ftp1.login(username1, password1))
            {
                System.err.println("Could not login to " + server1);
                break __main;
            }

            if (!ftp2.login(username2, password2))
            {
                System.err.println("Could not login to " + server2);
                break __main;
            }

            // Let's just assume success for now.
            ftp2.enterRemotePassiveMode();

            ftp1.enterRemoteActiveMode(InetAddress.getByName(ftp2.getPassiveHost()),
                                       ftp2.getPassivePort());

            // Although you would think the store command should be sent to server2
            // first, in reality, ftp servers like wu-ftpd start accepting data
            // connections right after entering passive mode.  Additionally, they
            // don't even send the positive preliminary reply until after the
            // transfer is completed (in the case of passive mode transfers).
            // Therefore, calling store first would hang waiting for a preliminary
            // reply.
            if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2))
            {
                //      if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) {
                // We have to fetch the positive completion reply.
                ftp1.completePendingCommand();
                ftp2.completePendingCommand();
            }
            else
            {
                System.err.println(
                    "Couldn't initiate transfer.  Check that filenames are valid.");
                break __main;
            }

        }
        catch (IOException e)
        {
            e.printStackTrace();
            System.exit(1);
        }
        finally
        {
            try
            {
                if (ftp1.isConnected())
                {
                    ftp1.logout();
                    ftp1.disconnect();
                }
            }
            catch (IOException e)
            {
                // do nothing
View Full Code Here

    public static final void main(String[] args)
    {
        int base = 0;
        boolean storeFile = false, binaryTransfer = false, error = false;
        String server, username, password, remote, local;
        FTPClient ftp;

        for (base = 0; base < args.length; base++)
        {
            if (args[base].startsWith("-s"))
                storeFile = true;
            else if (args[base].startsWith("-b"))
                binaryTransfer = true;
            else
                break;
        }

        if ((args.length - base) != 5)
        {
            System.err.println(USAGE);
            System.exit(1);
        }

        server = args[base++];
        username = args[base++];
        password = args[base++];
        remote = args[base++];
        local = args[base];

        ftp = new FTPClient();
        ftp.addProtocolCommandListener(new PrintCommandListener(
                                           new PrintWriter(System.out)));

        try
        {
            int reply;
            ftp.connect(server);
            System.out.println("Connected to " + server + ".");

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

            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                System.err.println("FTP server refused connection.");
                System.exit(1);
            }
        }
        catch (IOException e)
        {
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException f)
                {
                    // do nothing
                }
            }
            System.err.println("Could not connect to server.");
            e.printStackTrace();
            System.exit(1);
        }

__main:
        try
        {
            if (!ftp.login(username, password))
            {
                ftp.logout();
                error = true;
                break __main;
            }

            System.out.println("Remote system is " + ftp.getSystemName());

            if (binaryTransfer)
                ftp.setFileType(FTP.BINARY_FILE_TYPE);

            // Use passive mode as default because most of us are
            // behind firewalls these days.
            ftp.enterLocalPassiveMode();

            if (storeFile)
            {
                InputStream input;

                input = new FileInputStream(local);

                ftp.storeFile(remote, input);

                input.close();
            }
            else
            {
                OutputStream output;

                output = new FileOutputStream(local);

                ftp.retrieveFile(remote, output);

                output.close();
            }

            ftp.logout();
        }
        catch (FTPConnectionClosedException e)
        {
            error = true;
            System.err.println("Server closed connection.");
            e.printStackTrace();
        }
        catch (IOException e)
        {
            error = true;
            e.printStackTrace();
        }
        finally
        {
            if (ftp.isConnected())
            {
                try
                {
                    ftp.disconnect();
                }
                catch (IOException f)
                {
                    // do nothing
                }
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.