package com.ozs.da.utils.ftp;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @author 宋显哲
 * @version 1.0.0 创建于 2018/8/20
 **/
public class FtpClientFactory extends BasePooledObjectFactory<FTPClient> {
    private static Logger logger = LogManager.getLogger(FtpClientFactory.class);
    private FtpConfiguration configuration;

    public FtpClientFactory(FtpConfiguration configuration) {
        this.configuration = configuration;
    }

    @Override
    public FTPClient create() throws Exception {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.setConnectTimeout(configuration.getConnectTimeOut());
            ftpClient.setControlKeepAliveTimeout(1000);
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.connect(configuration.getHost(), configuration.getPort());
            boolean login = ftpClient.login(configuration.getUsername(), configuration.getPassword());
            if (!login) {
                logger.error("ftpClient登陆失败!");
                throw new Exception("ftpClient登陆失败! username:" + configuration.getUsername() + " ; password:"
                        + configuration.getPassword());
            }
            if (configuration.isPassiveMode()) {
                ftpClient.enterLocalPassiveMode();
            }
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            return ftpClient;
        } catch (Exception e) {
            logger.error("创建ftp连接错误 {}", e);
            return ftpClient;
        }

    }

    @Override
    public PooledObject<FTPClient> wrap(FTPClient ftpClient) {
        return new DefaultPooledObject<FTPClient>(ftpClient);
    }

    @Override
    public void destroyObject(PooledObject<FTPClient> p) throws Exception {
        FTPClient ftpClient = p.getObject();
        ftpClient.logout();
        ftpClient.disconnect();
        super.destroyObject(p);
    }

    @Override
    public boolean validateObject(PooledObject<FTPClient> p) {
        FTPClient ftpClient = p.getObject();
        try {
            return ftpClient.sendNoOp();
        } catch (Exception e) {
            logger.error("ftp-->{}", e);
            return false;
        }
    }
}
