⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 filetransferclient.java

📁 java ftp 鞭策帮手 可一啊啊觉得上
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/**
 * 
 *  Copyright (C) 2007 Enterprise Distributed Technologies Ltd
 *
 *  www.enterprisedt.com
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  Bug fixes, suggestions and comments should be should posted on 
 *  http://www.enterprisedt.com/forums/index.php
 *
 *  Change Log:
 *
 *    $Log: FileTransferClient.java,v $
 *    Revision 1.3  2008-01-09 03:54:21  bruceb
 *    executeCommand() now returns reply code
 *
 *    Revision 1.2  2007-12-20 00:40:16  bruceb
 *    autologin
 *
 *    Revision 1.1  2007-12-18 07:52:06  bruceb
 *    2.0 changes
 *
 *
 */
package com.enterprisedt.net.ftp;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

import com.enterprisedt.util.debug.Logger;

/**
 * Easy to use FTP client that is thread safe and provides true FTP streams.
 * This class is intended to replace FTPClient, which will eventually be
 * deprecated. 
 * 
 * @author Bruce Blackshaw
 * @version $Revision: 1.3 $
 */
public class FileTransferClient {
    
    private Logger log = Logger.getLogger("FileTransferClient");
    
    /**
     * Context for the client that is the starting point for all 
     * new tasks. If we have a change directory task, when it is completed
     * it will update this master context and the updated context will be used
     * for all future tasks
     */
    protected ConnectionContext masterContext = new ConnectionContext();
    
    protected EventAggregator eventAggregator = null;
        
    /**
     * Event listeners
     */
    protected EventListener listener;
    
    /**
     * Instance of FTPClient 
     */
    private FTPClient ftpClient = new FTPClient();
    
    /**
     * Advanced configuration parameters that often aren't used
     */
    private AdvancedFTPSettings advancedSettings;
    
    private FileStatistics statistics;
    
    /**
     * Default constructor
     */
    public FileTransferClient() {
        advancedSettings = new AdvancedFTPSettings(masterContext);
        statistics = new FileStatistics(ftpClient);
    } 
    
    /**
     * Checks if the client has connected to the server and throws an exception if it hasn't.
     * This is only intended to be used by subclasses
     * 
     * @throws FTPException Thrown if the client has not connected to the server.
     */
    protected void checkConnection(boolean shouldBeConnected) throws FTPException {
        if (shouldBeConnected && !isConnected())
            throw new FTPException("The file transfer client has not yet connected to the server.  "
                    + "The requested action cannot be performed until after a connection has been established.");
        else if (!shouldBeConnected && isConnected())
            throw new FTPException("The file transfer client has already been connected to the server.  "
                    +"The requested action must be performed before a connection is established.");
    }    
        
    /**
     * Is this client currently connected to the server?
     * 
     * @return  true if connected, false otherwise
     */
    public synchronized boolean isConnected() {
        return ftpClient.connected();
    }

    
    /**
     * Returns the IP address or name of the remote host.
     * 
     * @return Returns the remote host.
     */
    public synchronized String getRemoteHost() {
        return masterContext.getRemoteHost();
    }

    /**
     * Set the IP address or name of the remote host
     * 
     * This may only be done if the client is not already connected to the server.
     * 
     * @param remoteHost The IP address or name of the remote host
     * @throws FTPException Thrown if the client is already connected to the server.
     */
    public synchronized void setRemoteHost(String remoteHost) throws FTPException {
        checkConnection(false);
        masterContext.setRemoteHost(remoteHost);
    }
    
    /**
     * Returns the timeout for socket connections. 
     * 
     * @return Returns the connection timeout in milliseconds
     */
    public synchronized int getTimeout() {
        return masterContext.getTimeout();
    }
    
    /** 
     * Set the timeout for socket connections. Can only do this if
     * not already connected.
     * 
     * @param timeout  the timeout to use in milliseconds
     * @throws FTPException Thrown if the client is already connected to the server.
     */
    public synchronized void setTimeout(int timeout) throws FTPException {
        checkConnection(false);
        masterContext.setTimeout(timeout);
    }

    /**
     * Returns the port being connected to on the remote server. 
     * 
     * @return Returns the port being connected to on the remote server. 
     */
    public synchronized int getRemotePort() {
        return masterContext.getRemotePort();
    }
    
    /** 
     * Set the port to connect to on the remote server. Can only do this if
     * not already connected.
     * 
     * @param remotePort The port to use. 
     * @throws FTPException Thrown if the client is already connected to the server.
     */
    public synchronized void setRemotePort(int remotePort) throws FTPException {
        checkConnection(false);
        masterContext.setRemotePort(remotePort);
    }
    
    /**
     * Set the transfer type for all connections, either ASCII or binary. Setting
     * applies to all subsequent transfers that are initiated.
     * 
     * @param type            transfer type
     * @throws FTPException 
     * @throws IOException 
     * @throws FTPException
     */
    public synchronized void setContentType(FTPTransferType type) 
        throws IOException, FTPException {
        masterContext.setContentType(type);
        if (ftpClient.connected())
            ftpClient.setType(type);
    }
    
    /**
     * Get the current content type for all connections.
     * 
     * @return  transfer type
     */
    public synchronized FTPTransferType getContentType() {
        return masterContext.getContentType();
    }
    
    /**
     * Set auto detect of filetypes on or off. If on, the transfer mode is
     * switched from ASCII to binary and vice versa depending on the extension
     * of the file. After the transfer, the mode is always returned to what it
     * was before the transfer was performed. The default is off.
     * 
     * If the filetype is unknown, the transfer mode is unchanged
     * 
     * @param detectContentType    true if detecting content type, false if not
     */
    public void setDetectContentType(boolean detectContentType) {
        masterContext.setDetectContentType(detectContentType);
        ftpClient.setDetectTransferMode(detectContentType);
    }
    
    /**
     * Get the detect content type flag
     * 
     * @return true if we are detecting binary and ASCII transfers from the file type
     */
    public boolean getDetectContentType() {
        return masterContext.getDetectContentType();
    }
    
    /**
     * Set the name of the user to log in with. Can only do this if
     * not already connected.
     * 
     * @param userName          user-name to log in with.
     * @throws FTPException
     */
    public synchronized void setUserName(String userName) throws FTPException {
        checkConnection(false);
        masterContext.setUserName(userName);
    }
    
    /**
     * Get the current user password.
     * 
     * @return current user password
     */
    public synchronized String getPassword() {
        return masterContext.getPassword();
    }
    
    /**
     * Set the password of the user to log in with. Can only do this if
     * not already connected.
     * 
     * @param password          password to log in with.
     * @throws FTPException
     */
    public synchronized void setPassword(String password) throws FTPException {
        checkConnection(false);
        masterContext.setPassword(password);
    }
    
    /**
     * Get the current user name.
     * 
     * @return current user name
     */
    public synchronized String getUserName() {
        return masterContext.getUserName();
    }
    
    /**
     * Get the advanced configuration parameters object
     * 
     * @return advanced parameters
     */
    public synchronized AdvancedFTPSettings getAdvancedFTPSettings() {
        return advancedSettings;        
    }
    
    /**
     * Set the event listener for transfer event notification
     * 
     * @param listener  event listener reference
     */
    public synchronized void setEventListener(EventListener listener) {
        this.listener = listener;
        eventAggregator = new EventAggregator(listener);
        ftpClient.setMessageListener(eventAggregator);
        ftpClient.setProgressMonitor(eventAggregator);
        ftpClient.setProgressMonitorEx(eventAggregator);
    }
    
    /**
     * Make a connection to the FTP server. 
     * 
     * @throws FTPException 
     * @throws IOException 
     */
    public synchronized void connect() throws FTPException, IOException {
        configureClient();
        log.debug("Configured client");
        ftpClient.connect();
        log.debug("Client connected");
        if (masterContext.isAutoLogin()) {
            log.debug("Logging in");
            ftpClient.login(masterContext.getUserName(), masterContext.getPassword());
            log.debug("Logged in");
            configureTransferType(masterContext.getContentType());
        }
        else {
            log.debug("Manual login enabled");
        }
    }
    
    /**
     * Perform a manual login using the credentials that have been set. This
     * should only be performed if auto login is disabled - normally connect()
     * performs the login automatically.
     * 
     * @throws FTPException
     * @throws IOException
     */
    public void manualLogin() throws FTPException, IOException {
        checkConnection(true);
        log.debug("Logging in");
        ftpClient.login(masterContext.getUserName(), masterContext.getPassword());
        log.debug("Logged in");
        configureTransferType(masterContext.getContentType());
    }
    
    /**
     * Apply the master context's settings to the client
     * 
     * @throws IOException
     * @throws FTPException
     */
    protected void configureClient() throws IOException, FTPException {
        ftpClient.setRemoteHost(masterContext.getRemoteHost());
        ftpClient.setRemotePort(masterContext.getRemotePort());
        ftpClient.setTimeout(masterContext.getTimeout());       
        ftpClient.setControlEncoding(masterContext.getControlEncoding());
        ftpClient.setStrictReturnCodes(masterContext.isStrictReturnCodes());
        ftpClient.setDetectTransferMode(masterContext.getDetectContentType());
        ftpClient.setConnectMode(masterContext.getConnectMode());
        ftpClient.setParserLocales(masterContext.getParserLocales());
        ftpClient.setAutoPassiveIPSubstitution(masterContext.isAutoPassiveIPSubstitution());
        ftpClient.setDeleteOnFailure(masterContext.isDeleteOnFailure());
        ftpClient.setActiveIPAddress(masterContext.getActiveIPAddress());
        ftpClient.setMonitorInterval(masterContext.getTransferNotifyInterval());
        ftpClient.setTransferBufferSize(masterContext.getTransferBufferSize());
        if (masterContext.getActiveHighPort() >= 0 && masterContext.getActiveLowPort() >= 0)
            ftpClient.setActivePortRange(masterContext.getActiveLowPort(), masterContext.getActiveHighPort());
    }
    
    
    protected void configureTransferType(FTPTransferType type) 
        throws IOException, FTPException {
        ftpClient.setDetectTransferMode(masterContext.getDetectContentType());
        ftpClient.setType(type);
    }
    
    protected void checkTransferSettings() throws FTPException {
        
        if (ftpClient.getDetectTransferMode() != masterContext.getDetectContentType())
            ftpClient.setDetectTransferMode(masterContext.getDetectContentType());
        
        if (ftpClient.isStrictReturnCodes() != masterContext.isStrictReturnCodes())
            ftpClient.setStrictReturnCodes(masterContext.isStrictReturnCodes());
        
        if (!ftpClient.getConnectMode().equals(masterContext.getConnectMode()))
            ftpClient.setConnectMode(masterContext.getConnectMode());        
        
        if (ftpClient.isAutoPassiveIPSubstitution() != masterContext.isAutoPassiveIPSubstitution())
            ftpClient.setAutoPassiveIPSubstitution(masterContext.isAutoPassiveIPSubstitution());
        
        if (ftpClient.isDeleteOnFailure() != masterContext.isDeleteOnFailure())
            ftpClient.setDeleteOnFailure(masterContext.isDeleteOnFailure());
        
        if (ftpClient.getActiveIPAddress() != masterContext.getActiveIPAddress())
            ftpClient.setActiveIPAddress(masterContext.getActiveIPAddress());
        
        if (ftpClient.getTransferBufferSize() != masterContext.getTransferBufferSize())
            ftpClient.setTransferBufferSize(masterContext.getTransferBufferSize());
        
        if (ftpClient.getMonitorInterval() != masterContext.getTransferNotifyInterval())
            ftpClient.setMonitorInterval(masterContext.getTransferNotifyInterval());  
        
        if (masterContext.getActiveHighPort() != ftpClient.getActiveHighPort() ||
            masterContext.getActiveLowPort() != ftpClient.getActiveLowPort())
            ftpClient.setActivePortRange(masterContext.getActiveLowPort(), masterContext.getActiveHighPort());
    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -