package com.ozs.da.utils.ftp;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

/**
 * @author 宋显哲
 * @version 1.0.0 创建于 2018/8/20
 **/
public class FtpClientPool {
    private GenericObjectPool<FTPClient> ftpClientPool;
    private FtpConfiguration configuration;

    public FtpClientPool(FtpConfiguration configuration) {
        this.configuration = configuration;
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(configuration.getMaxIdle());
        poolConfig.setMaxTotal(configuration.getMaxTotal());
        poolConfig.setMinIdle(configuration.getMinIdle());
        poolConfig.setMaxWaitMillis(configuration.getMaxWaitMillis());
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnCreate(true);
        poolConfig.setTestOnReturn(true);
        ftpClientPool = new GenericObjectPool<FTPClient>(new FtpClientFactory(this.configuration), poolConfig);
    }

    /**
     * 获取FTP客户端
     *
     * @return
     */
    public FTPClient getFtpClient() {
        try {
            return ftpClientPool.borrowObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将ftp连接返回连接池
     *
     * @param ftpClient ftpClient
     */
    public void returnFtpClient(FTPClient ftpClient) {
        ftpClientPool.returnObject(ftpClient);
    }

}
