package com.chinaztt.mes.common.ftp; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import org.apache.commons.pool.BasePoolableObjectFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * @Author: zhangxy * @Date: 2019/12/10 8:45 */ public class FtpPoolAbleObjectFactory extends BasePoolableObjectFactory { private FtpClientConfigure ftpClientConfigure; private static Logger logger = LoggerFactory.getLogger(FtpPoolAbleObjectFactory.class); public FtpPoolAbleObjectFactory(FtpClientConfigure ftpClientConfigure) { this.ftpClientConfigure = ftpClientConfigure; } @Override public FTPClient makeObject() { logger.info("make client"); FTPClient ftpClient = new FTPClient(); String no = "ON"; String format = "OPTS UTF8"; try { ftpClient.setConnectTimeout(Integer.parseInt(ftpClientConfigure.getClientTimeout())); ftpClient.setDefaultTimeout(Integer.parseInt(ftpClientConfigure.getClientTimeout())); ftpClient.setDataTimeout(Integer.parseInt(ftpClientConfigure.getClientTimeout())); ftpClient.connect(ftpClientConfigure.getHost(), Integer.parseInt(ftpClientConfigure.getPort())); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); logger.error("FTPServer refused connection"); return null; } boolean result = ftpClient.login(ftpClientConfigure.getUsername(), ftpClientConfigure.getPassword()); if (!result) { throw new RuntimeException("ftpClient登陆失败"); } if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(format, no))) { ftpClient.setControlEncoding("UTF-8"); } else { ftpClient.setControlEncoding(ftpClientConfigure.getEncoding()); } ftpClient.setBufferSize(1024); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (ftpClientConfigure.getPassiveMode().equals(true)) { ftpClient.enterLocalPassiveMode(); } } catch (Exception e) { logger.error("make object error", e); } return ftpClient; } @Override public void destroyObject(FTPClient ftpClient) { try { if (ftpClient != null && ftpClient.isConnected()) { ftpClient.logout(); } } catch (IOException io) { logger.error("destory logout exception", io); } finally { try { if (ftpClient != null) { ftpClient.disconnect(); } } catch (Exception io) { logger.error("destory disconnect exception", io); } } } @Override public boolean validateObject(FTPClient ftpClient) { try { return ftpClient.sendNoOp(); } catch (IOException e) { logger.error("Failed to validate client:", e); return false; } } }