Commit 2c8f3c02 authored by neo.wang's avatar neo.wang

Merge branch 'dev_neo' into 'dev'

Dev neo

See merge request root/atms!58
parents ea74a6a8 19dafa28
...@@ -4,16 +4,19 @@ import org.apache.commons.lang3.StringUtils; ...@@ -4,16 +4,19 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import pwc.taxtech.atms.exception.ServiceException;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.io.IOException; import java.io.*;
import java.io.InputStream;
@Component @Component
public class FTPClientPool { public class FTPClientPool {
private static final Logger LOGGER = LoggerFactory.getLogger(FTPClientPool.class);
private GenericObjectPoolConfig config; private GenericObjectPoolConfig config;
private GenericObjectPool<FTPClient> pool; private GenericObjectPool<FTPClient> pool;
private String ftpRootPath; private String ftpRootPath;
...@@ -39,9 +42,17 @@ public class FTPClientPool { ...@@ -39,9 +42,17 @@ public class FTPClientPool {
clientConfig.setPassword(ftpPwd); clientConfig.setPassword(ftpPwd);
ftpClientConfig = clientConfig; ftpClientConfig = clientConfig;
pool = new GenericObjectPool<>(new FtpClientFactory(clientConfig), config); pool = new GenericObjectPool<>(new FtpClientFactory(clientConfig), config);
ftpRootPath = pool.borrowObject().printWorkingDirectory();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
pool.close();
}));
FTPClient client = pool.borrowObject();
ftpRootPath = client.printWorkingDirectory();
pool.returnObject(client);
} }
// this method should only be used in test
public FTPClient getClient() throws Exception { public FTPClient getClient() throws Exception {
return pool.borrowObject(); return pool.borrowObject();
} }
...@@ -56,8 +67,7 @@ public class FTPClientPool { ...@@ -56,8 +67,7 @@ public class FTPClientPool {
*/ */
public void upload(String filePath, String fileName, InputStream inputStream) throws Exception { public void upload(String filePath, String fileName, InputStream inputStream) throws Exception {
String upPath; String upPath;
FTPClient client = getClient(); try (WrapFtpClient wrapFtpClient = new WrapFtpClient(pool)) {
try {
if (StringUtils.isBlank(filePath)) { if (StringUtils.isBlank(filePath)) {
upPath = ftpRootPath; upPath = ftpRootPath;
} else { } else {
...@@ -66,12 +76,10 @@ public class FTPClientPool { ...@@ -66,12 +76,10 @@ public class FTPClientPool {
if (!StringUtils.endsWith(upPath, SYMBOL)) { if (!StringUtils.endsWith(upPath, SYMBOL)) {
upPath = upPath + SYMBOL; upPath = upPath + SYMBOL;
} }
if (!isExist(upPath, client)) { if (!isExist(upPath, wrapFtpClient.ftpClient)) {
mkDir(upPath, client); mkDir(upPath, wrapFtpClient.ftpClient);
} }
client.storeFile(upPath + fileName, inputStream); wrapFtpClient.ftpClient.storeFile(upPath + fileName, inputStream);
} finally {
pool.returnObject(client);
} }
} }
...@@ -83,13 +91,18 @@ public class FTPClientPool { ...@@ -83,13 +91,18 @@ public class FTPClientPool {
* @throws Exception Exception * @throws Exception Exception
*/ */
public InputStream download(String filePath) throws Exception { public InputStream download(String filePath) throws Exception {
FTPClient client = getClient(); try (WrapFtpClient wrapFtpClient = new WrapFtpClient(pool); OutputStream out = new ByteArrayOutputStream();) {
try { if (StringUtils.isBlank(filePath)) throw new ServiceException("file path should not empty");
client.changeWorkingDirectory(ftpRootPath); wrapFtpClient.ftpClient.changeWorkingDirectory(ftpRootPath);
return StringUtils.isBlank(filePath) ? null : client.retrieveFileStream(filePath); InputStream in = wrapFtpClient.ftpClient.retrieveFileStream(filePath);
} finally { int len = 0;
//pool.returnObject(client); byte[] bytes = new byte[1024];
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
return new ByteArrayInputStream(((ByteArrayOutputStream) out).toByteArray());
} }
} }
private void mkDir(String path, FTPClient ftpClient) throws IOException { private void mkDir(String path, FTPClient ftpClient) throws IOException {
...@@ -128,18 +141,15 @@ public class FTPClientPool { ...@@ -128,18 +141,15 @@ public class FTPClientPool {
* @param filePath * @param filePath
*/ */
public void delete(String filePath) throws Exception { public void delete(String filePath) throws Exception {
if (StringUtils.isBlank(filePath)) { try (WrapFtpClient wrapFtpClient = new WrapFtpClient(pool);) {
return; if (StringUtils.isBlank(filePath)) {
} return;
FTPClient client = getClient(); }
try { if (!isExist(filePath, wrapFtpClient.ftpClient)) {
if (!isExist(filePath, client)) {
return; return;
} else { } else {
client.deleteFile(filePath); wrapFtpClient.ftpClient.deleteFile(filePath);
} }
} finally {
pool.returnObject(client);
} }
} }
......
...@@ -21,6 +21,9 @@ public class FtpClientFactory implements PooledObjectFactory<FTPClient> { ...@@ -21,6 +21,9 @@ public class FtpClientFactory implements PooledObjectFactory<FTPClient> {
this.config = config; this.config = config;
} }
public FTPClientConfig getConfig() {
return config;
}
@Override @Override
public PooledObject<FTPClient> makeObject() throws Exception { public PooledObject<FTPClient> makeObject() throws Exception {
...@@ -28,33 +31,32 @@ public class FtpClientFactory implements PooledObjectFactory<FTPClient> { ...@@ -28,33 +31,32 @@ public class FtpClientFactory implements PooledObjectFactory<FTPClient> {
if (null != config.getClientTimeout()) { if (null != config.getClientTimeout()) {
ftpClient.setConnectTimeout(config.getClientTimeout()); ftpClient.setConnectTimeout(config.getClientTimeout());
} }
try { ftpClient.connect(config.getHost(), config.getPort());
ftpClient.connect(config.getHost(), config.getPort()); int reply = ftpClient.getReplyCode();
int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) {
if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect();
ftpClient.disconnect(); logger.warn("FTPServer refused connection");
logger.warn("FTPServer refused connection"); throw new ServiceException("FTPServer refused connection");
return null; }
} boolean result = ftpClient.login(StringUtils.defaultString(config.getUsername()),
boolean result = ftpClient.login(StringUtils.defaultString(config.getUsername()), StringUtils.defaultString(config.getPassword()));
StringUtils.defaultString(config.getPassword())); if (!result) {
if (!result) { throw new ServiceException("ftpClient登陆失败! userName:" + config.getUsername() + " ; password:" + config.getPassword());
throw new ServiceException("ftpClient登陆失败! userName:" + config.getUsername() + " ; password:" + config.getPassword()); }
} ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (null != config.getTransferFileType()) {
if (null != config.getTransferFileType()) { ftpClient.setFileType(config.getTransferFileType());
ftpClient.setFileType(config.getTransferFileType()); }
} ftpClient.setBufferSize(1024);
ftpClient.setBufferSize(1024); ftpClient.setControlEncoding(StringUtils.defaultString(config.getEncoding(), "UTF-8"));
ftpClient.setControlEncoding(StringUtils.defaultString(config.getEncoding(), "UTF-8")); ftpClient.enterLocalPassiveMode();
ftpClient.enterLocalPassiveMode();
// if (StringUtils.equals(config.getPassiveMode(), "true")) { // if (StringUtils.equals(config.getPassiveMode(), "true")) {
// ftpClient.enterLocalPassiveMode(); // ftpClient.enterLocalPassiveMode();
// } // }
} catch (Exception e) {
logger.error("create ftp client error", e); logger.debug("mk objec ftp client {}", ftpClient.toString());
}
return new DefaultPooledObject<>(ftpClient); return new DefaultPooledObject<>(ftpClient);
} }
@Override @Override
...@@ -62,13 +64,13 @@ public class FtpClientFactory implements PooledObjectFactory<FTPClient> { ...@@ -62,13 +64,13 @@ public class FtpClientFactory implements PooledObjectFactory<FTPClient> {
FTPClient ftpClient = pooledObject.getObject(); FTPClient ftpClient = pooledObject.getObject();
try { try {
if (ftpClient != null && ftpClient.isConnected()) { if (ftpClient != null && ftpClient.isConnected()) {
logger.debug("destroy ftp client {}", ftpClient.toString());
ftpClient.logout(); ftpClient.logout();
} }
} catch (IOException io) {
io.printStackTrace();
} finally { } finally {
try { try {
ftpClient.disconnect(); if (ftpClient != null && ftpClient.isConnected())
ftpClient.disconnect();
} catch (IOException io) { } catch (IOException io) {
io.printStackTrace(); io.printStackTrace();
} }
...@@ -78,6 +80,12 @@ public class FtpClientFactory implements PooledObjectFactory<FTPClient> { ...@@ -78,6 +80,12 @@ public class FtpClientFactory implements PooledObjectFactory<FTPClient> {
@Override @Override
public boolean validateObject(PooledObject<FTPClient> pooledObject) { public boolean validateObject(PooledObject<FTPClient> pooledObject) {
try { try {
logger.debug("validate object ftp client {} ", pooledObject.getObject().toString());
FTPClient ftpClient = pooledObject.getObject();
if (ftpClient == null || !ftpClient.isConnected()) {
return false;
}
ftpClient.changeWorkingDirectory("/");
return pooledObject.getObject().sendNoOp(); return pooledObject.getObject().sendNoOp();
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to validate client: " + e, e); throw new RuntimeException("Failed to validate client: " + e, e);
...@@ -86,12 +94,12 @@ public class FtpClientFactory implements PooledObjectFactory<FTPClient> { ...@@ -86,12 +94,12 @@ public class FtpClientFactory implements PooledObjectFactory<FTPClient> {
@Override @Override
public void activateObject(PooledObject<FTPClient> pooledObject) throws Exception { public void activateObject(PooledObject<FTPClient> pooledObject) throws Exception {
logger.debug("activateObject {}", pooledObject.getObject().toString());
} }
@Override @Override
public void passivateObject(PooledObject<FTPClient> pooledObject) throws Exception { public void passivateObject(PooledObject<FTPClient> pooledObject) throws Exception {
logger.debug("passivateObject {}", pooledObject.getObject().toString());
} }
} }
package pwc.taxtech.atms.common.ftp;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;
public class WrapFtpClient implements AutoCloseable {
FTPClient ftpClient;
GenericObjectPool<FTPClient> pool;
public WrapFtpClient(GenericObjectPool<FTPClient> pool) throws Exception {
this.pool = pool;
this.ftpClient = pool.borrowObject();
}
public FTPClient getFtpClient() {
return ftpClient;
}
@Override
public void close() throws Exception {
ftpClient.completePendingCommand();
pool.returnObject(ftpClient);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment