package com.vcredit.ddcash.server.commons.net;

import com.vcredit.ddcash.server.commons.model.FtpParam;
import org.apache.commons.net.ftp.*;
import org.apache.commons.net.ftp.parser.MLSxEntryParser;
import org.apache.commons.net.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.*;
import java.util.ArrayList;

/**
* Created by guanshuli on 2017/2/7.
*/

public class FTPClient extends org.apache.commons.net.ftp.FTPClient {
private static final Logger logger = LoggerFactory.getLogger(FTPClient.class);
public String __systemName;
public boolean __autodetectEncoding = false;
public int __dataConnectionMode;
public int __fileType;
public boolean __remoteVerificationEnabled;
public int __controlKeepAliveReplyTimeout = 1000;
public long __controlKeepAliveTimeout;
public int __fileFormat;
public int __bufferSize;
public CopyStreamListener __copyStreamListener;
public int receiveBufferSize = -1;
public int sendBufferSize = -1;

static String __parsePathname(String reply) {
String param = reply.substring(4);
if (param.startsWith("\"")) {
StringBuilder sb = new StringBuilder();
boolean quoteSeen = false;

for (int i = 1; i < param.length(); ++i) {
char ch = param.charAt(i);
if (ch == 34) {
if (quoteSeen) {
sb.append(ch);
quoteSeen = false;
} else {
quoteSeen = true;
}
} else {
if (quoteSeen) {
return sb.toString();
}

sb.append(ch);
}
}

if (quoteSeen) {
return sb.toString();
}
}

return param;
}

public void closeFtpClient() throws IOException {
this.logout();
if (this.isAvailable()) {
this.disconnect();
}
}

public boolean exists(String pathname) throws IOException {
return this.listNames(pathname).length > 0;
}

public boolean existsDir(String fileName) throws IOException {
return this.listDirectories(fileName).length >0;
}

public boolean isFile(String fileName) throws IOException {
return this.listFiles(fileName)[0].isFile();
}

public FTPFile getFile(String fileName) throws IOException {
return this.listFiles(fileName)[0];
}

public void connect(InetAddress host, int port) throws IOException {
this._socket_ = this._socketFactory_.createSocket();
if (this.receiveBufferSize != -1) {
this._socket_.setReceiveBufferSize(this.receiveBufferSize);
}

if (this.sendBufferSize != -1) {
this._socket_.setSendBufferSize(this.sendBufferSize);
}
this._socket_.connect(new InetSocketAddress(host, port), this.connectTimeout);
this._connectAction_();
}

private boolean __storeFile(FTPCmd command, String remote, InputStream local) throws IOException {
return this._storeFile(command.getCommand(), remote, local);
}

protected boolean _storeFile(String command, String remote, InputStream local) throws IOException {
Socket socket = this._openDataConnection_(command, remote);
if (socket == null) {
return false;
} else {
Object output = this.getBufferedOutputStream(socket.getOutputStream());
if (this.__fileType == 0) {
output = new ToNetASCIIOutputStream((OutputStream) output);
}

CSL csl = null;
if (this.__controlKeepAliveTimeout > 0L) {
csl = new CSL(this, this.__controlKeepAliveTimeout, this.__controlKeepAliveReplyTimeout);
}
this.setBufferSize(8*1024);
try {
Util.copyStream(local, (OutputStream) output, this.getBufferSize(), -1L, this.__mergeListeners(csl), true);
} catch (IOException var8) {
Util.closeQuietly(socket);
if (csl != null) {
csl.cleanUp();
}

throw var8;
}

((OutputStream) output).close();
socket.close();
if (csl != null) {
csl.cleanUp();
}

return this.completePendingCommand();
}
}

private CopyStreamListener __mergeListeners(CopyStreamListener local) {
if (local == null) {
return this.__copyStreamListener;
} else if (this.__copyStreamListener == null) {
return local;
} else {
CopyStreamAdapter merged = new CopyStreamAdapter();
merged.addCopyStreamListener(local);
merged.addCopyStreamListener(this.__copyStreamListener);
return merged;
}
}

private OutputStream __storeFileStream(FTPCmd command, String remote) throws IOException {
return this._storeFileStream(command.getCommand(), remote);
}

private OutputStream getBufferedOutputStream(OutputStream outputStream) {
return this.__bufferSize > 0 ? new BufferedOutputStream(outputStream, this.__bufferSize) : new BufferedOutputStream(outputStream);
}

protected OutputStream _storeFileStream(String command, String remote) throws IOException {
Socket socket = this._openDataConnection_(command, remote);
if (socket == null) {
return null;
} else {
Object output = socket.getOutputStream();
if (this.__fileType == 0) {
OutputStream output1 = this.getBufferedOutputStream((OutputStream) output);
output = new ToNetASCIIOutputStream(output1);
}

return new SocketOutputStream(socket, (OutputStream) output);
}
}

//上传用户身份证图片 ftp
public boolean uploadImg(String identityPath,FtpParam ftpParam, InputStream inputStream) throws IOException {
//设置上传目录
boolean flag;
logger.info("ftp uploadImg before url:" + ftpParam.getIdentityPath() + ftpParam.getSubDir() + "fileName:" + ftpParam.getFileName());
if (!changeWorkingDirectory(identityPath + ftpParam.getSubDir())) {
if (createDirectory(identityPath, ftpParam.getSubDir())) {
setControlEncoding("GBK");
setFileType(BINARY_FILE_TYPE);
setBufferSize(8 * 1024);
logger.info("ftp uploadImg storeFile url:" + ftpParam.getIdentityPath() + ftpParam.getSubDir() + "fileName:" + ftpParam.getFileName());
storeFile(new String(ftpParam.getFileName().getBytes("UTF-8"),"iso-8859-1"), inputStream);
flag = true;
} else {
flag = false;
}
} else {
setControlEncoding("GBK");
//设置文件类型(二进制)
setFileType(BINARY_FILE_TYPE);
setBufferSize(8 * 1024);
storeFile(new String(ftpParam.getFileName().getBytes("UTF-8"),"iso-8859-1"), inputStream);
flag = true;
}
logger.info("ftp uploadImg after url:" + ftpParam.getIdentityPath() + ftpParam.getSubDir() + "fileName:" + ftpParam.getFileName());
return flag;
}

//此方法不要单独使用 注意 logout(); disconnect();
public boolean createDirectory(String rootPath, String subDir) throws IOException {
changeWorkingDirectory(rootPath);
//如果远程目录不存在,则递归创建远程服务器目录
int start = 0;
int index = subDir.indexOf("/", start);
//日志记录,增加了什么目录
String addedPath = "";
while (true) {
String dir = subDir.substring(start, index);
if (!changeWorkingDirectory(new String(dir.getBytes("GBK"), "iso-8859-1"))) {
if (makeDirectory(dir)) {
addedPath +="/"+ dir;
changeWorkingDirectory(dir);
} else {
return false;
}
}
start = index + 1;
index = subDir.indexOf("/", start);
//检查所有目录是否创建完毕
if (start >= index) {
break;
}
}
logger.info("ftp createDirectory,rootPath:"+rootPath+"subDir:"+subDir+", addedPath"+addedPath);
return true;
}

/**
* Removes a non-empty directory by delete all its sub files and
* sub directories recursively. And finally remove the directory.
*/
public void removeDirectory(String parentDir,
String currentDir) throws IOException {
String dirToList = parentDir;
if (!currentDir.equals("")) {
dirToList += "/" + currentDir;
}

FTPFile[] subFiles = listFiles(dirToList);

if (subFiles != null && subFiles.length > 0) {
for (FTPFile aFile : subFiles) {
String currentFileName = aFile.getName();
if (currentFileName.equals(".") || currentFileName.equals("..")) {
// skip parent directory and the directory itself
continue;
}
String filePath = parentDir + currentDir
+ currentFileName;
if (currentDir.equals("")) {
filePath = parentDir + currentFileName;
}

if (aFile.isDirectory()) {
// remove the sub directory
removeDirectory(dirToList, currentFileName);
} else {
// delete the file
boolean deleted = deleteFile(filePath);
if (deleted) {
System.out.println("DELETED the file: " + filePath);
} else {
System.out.println("CANNOT delete the file: "
+ filePath);
}
}
}

// finally, remove the directory itself
boolean removed = removeDirectory(dirToList);
if (removed) {
System.out.println("REMOVED the directory: " + dirToList);
} else {
System.out.println("CANNOT remove the directory: " + dirToList);
}
}
}

/**
* @deprecated
*/
@Deprecated
protected Socket _openDataConnection_(int command, String arg) throws IOException {
return this._openDataConnection_(FTPCommand.getCommand(command), arg);
}

protected Socket _openDataConnection_(FTPCmd command, String arg) throws IOException {
return this._openDataConnection_(command.getCommand(), arg);
}

private void __initDefaults() {
this.__dataConnectionMode = 0;
this.__fileType = 0;
this.__fileFormat = 4;
this.__systemName = null;
}

protected void _connectAction_() throws IOException {
super._connectAction_();
this.__initDefaults();
if (this.__autodetectEncoding) {
ArrayList oldReplyLines = new ArrayList(this._replyLines);
int oldReplyCode = this._replyCode;
if (this.hasFeature("UTF8") || this.hasFeature("UTF-8")) {
this.setControlEncoding("UTF-8");
this._controlInput_ = new CRLFLineReader(new InputStreamReader(this._input_, this.getControlEncoding()));
this._controlOutput_ = new BufferedWriter(new OutputStreamWriter(this._output_, this.getControlEncoding()));
}

this._replyLines.clear();
this._replyLines.addAll(oldReplyLines);
this._replyCode = oldReplyCode;
}

}

public void disconnect() throws IOException {
super.disconnect();
this.__initDefaults();
}

public void setRemoteVerificationEnabled(boolean enable) {
this.__remoteVerificationEnabled = enable;
}

public boolean isRemoteVerificationEnabled() {
return this.__remoteVerificationEnabled;
}

public boolean login(String username, String password) throws IOException {
this.user(username);
return FTPReply.isPositiveCompletion(this._replyCode) ? true : (!FTPReply.isPositiveIntermediate(this._replyCode) ? false : FTPReply.isPositiveCompletion(this.pass(password)));
}

public boolean login(String username, String password, String account) throws IOException {
this.user(username);
if (FTPReply.isPositiveCompletion(this._replyCode)) {
return true;
} else if (!FTPReply.isPositiveIntermediate(this._replyCode)) {
return false;
} else {
this.pass(password);
return FTPReply.isPositiveCompletion(this._replyCode) ? true : (!FTPReply.isPositiveIntermediate(this._replyCode) ? false : FTPReply.isPositiveCompletion(this.acct(account)));
}
}

public boolean logout() throws IOException {
return FTPReply.isPositiveCompletion(this.quit());
}

public boolean changeWorkingDirectory(String pathname) throws IOException {
return FTPReply.isPositiveCompletion(this.cwd(pathname));
}

public boolean changeToParentDirectory() throws IOException {
return FTPReply.isPositiveCompletion(this.cdup());
}

public boolean structureMount(String pathname) throws IOException {
return FTPReply.isPositiveCompletion(this.smnt(pathname));
}

public boolean setFileType(int fileType) throws IOException {
if (FTPReply.isPositiveCompletion(this.type(fileType))) {
this.__fileType = fileType;
this.__fileFormat = 4;
return true;
} else {
return false;
}
}

public boolean setFileType(int fileType, int formatOrByteSize) throws IOException {
if (FTPReply.isPositiveCompletion(this.type(fileType, formatOrByteSize))) {
this.__fileType = fileType;
this.__fileFormat = formatOrByteSize;
return true;
} else {
return false;
}
}

public boolean remoteRetrieve(String filename) throws IOException {
return this.__dataConnectionMode != 1 && this.__dataConnectionMode != 3 ? false : FTPReply.isPositivePreliminary(this.retr(filename));
}

public boolean remoteStore(String filename) throws IOException {
return this.__dataConnectionMode != 1 && this.__dataConnectionMode != 3 ? false : FTPReply.isPositivePreliminary(this.stor(filename));
}

public boolean remoteStoreUnique(String filename) throws IOException {
return this.__dataConnectionMode != 1 && this.__dataConnectionMode != 3 ? false : FTPReply.isPositivePreliminary(this.stou(filename));
}

public boolean remoteStoreUnique() throws IOException {
return this.__dataConnectionMode != 1 && this.__dataConnectionMode != 3 ? false : FTPReply.isPositivePreliminary(this.stou());
}

public boolean remoteAppend(String filename) throws IOException {
return this.__dataConnectionMode != 1 && this.__dataConnectionMode != 3 ? false : FTPReply.isPositivePreliminary(this.appe(filename));
}

public boolean completePendingCommand() throws IOException {
return FTPReply.isPositiveCompletion(this.getReply());
}

public boolean retrieveFile(String remote, OutputStream local) throws IOException {
return this._retrieveFile(FTPCmd.RETR.getCommand(), remote, local);
}

public boolean storeFile(String remote, InputStream local) throws IOException {
return this.__storeFile(FTPCmd.STOR, remote, local);
}

public OutputStream storeFileStream(String remote) throws IOException {
return this.__storeFileStream(FTPCmd.STOR, remote);
}

public OutputStream appendFileStream(String remote) throws IOException {
return this.__storeFileStream(FTPCmd.APPE, remote);
}

public FTPFile[] mlistDir() throws IOException {
return this.mlistDir((String) null);
}

public FTPFile[] mlistDir(String pathname) throws IOException {
FTPListParseEngine engine = this.initiateMListParsing(pathname);
return engine.getFiles();
}

public FTPFile[] mlistDir(String pathname, FTPFileFilter filter) throws IOException {
FTPListParseEngine engine = this.initiateMListParsing(pathname);
return engine.getFiles(filter);
}

public boolean deleteFile(String pathname) throws IOException {
return FTPReply.isPositiveCompletion(this.dele(pathname));
}

public boolean removeDirectory(String pathname) throws IOException {
return FTPReply.isPositiveCompletion(this.rmd(pathname));
}

public boolean makeDirectory(String pathname) throws IOException {
return FTPReply.isPositiveCompletion(this.mkd(pathname));
}

public String printWorkingDirectory() throws IOException {
return this.pwd() != 257 ? null : __parsePathname((String) this._replyLines.get(this._replyLines.size() - 1));
}

public boolean sendSiteCommand(String arguments) throws IOException {
return FTPReply.isPositiveCompletion(this.site(arguments));
}

public String getSystemType() throws IOException {
if (this.__systemName == null) {
if (FTPReply.isPositiveCompletion(this.syst())) {
this.__systemName = ((String) this._replyLines.get(this._replyLines.size() - 1)).substring(4);
} else {
String systDefault = System.getProperty("org.apache.commons.net.ftp.systemType.default");
if (systDefault == null) {
throw new IOException("Unable to determine system type - response: " + this.getReplyString());
}

this.__systemName = systDefault;
}
}

return this.__systemName;
}

public String listHelp() throws IOException {
return FTPReply.isPositiveCompletion(this.help()) ? this.getReplyString() : null;
}

public String listHelp(String command) throws IOException {
return FTPReply.isPositiveCompletion(this.help(command)) ? this.getReplyString() : null;
}

public boolean sendNoOp() throws IOException {
return FTPReply.isPositiveCompletion(this.noop());
}

public String[] listNames(String pathname) throws IOException {
Socket socket = this._openDataConnection_(FTPCmd.NLST, this.getListArguments(pathname));
if (socket == null) {
return null;
} else {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), this.getControlEncoding()));
ArrayList results = new ArrayList();

String line;
while ((line = reader.readLine()) != null) {
results.add(line);
}

reader.close();
socket.close();
if (this.completePendingCommand()) {
String[] names = new String[results.size()];
return (String[]) results.toArray(names);
} else {
return null;
}
}
}

public FTPFile[] listFiles(String pathname) throws IOException {
FTPListParseEngine engine = this.initiateListParsing((String) null, pathname);
return engine.getFiles();
}

public FTPFile[] listFiles(String pathname, FTPFileFilter filter) throws IOException {
FTPListParseEngine engine = this.initiateListParsing((String) null, pathname);
return engine.getFiles(filter);
}

public FTPFile[] listDirectories(String parent) throws IOException {
return this.listFiles(parent, FTPFileFilters.DIRECTORIES);
}

public FTPListParseEngine initiateListParsing(String pathname) throws IOException {
return this.initiateListParsing((String) null, pathname);
}

private FTPListParseEngine initiateMListParsing(String pathname) throws IOException {
Socket socket = this._openDataConnection_(FTPCmd.MLSD, pathname);
FTPListParseEngine engine = new FTPListParseEngine(MLSxEntryParser.getInstance());
if (socket == null) {
return engine;
} else {
try {
engine.readServerList(socket.getInputStream(), this.getControlEncoding());
} finally {
Util.closeQuietly(socket);
this.completePendingCommand();
}

return engine;
}
}

protected String getListArguments(String pathname) {
if (this.getListHiddenFiles()) {
if (pathname != null) {
StringBuilder sb = new StringBuilder(pathname.length() + 3);
sb.append("-a ");
sb.append(pathname);
return sb.toString();
} else {
return "-a";
}
} else {
return pathname;
}
}

public void setAutodetectUTF8(boolean autodetect) {
this.__autodetectEncoding = autodetect;
}

public boolean getAutodetectUTF8() {
return this.__autodetectEncoding;
}

/**
* @deprecated
*/
@Deprecated
public String getSystemName() throws IOException {
if (this.__systemName == null && FTPReply.isPositiveCompletion(this.syst())) {
this.__systemName = ((String) this._replyLines.get(this._replyLines.size() - 1)).substring(4);
}

return this.__systemName;
}

private static class CSL implements CopyStreamListener {
private final FTPClient parent;
private final long idle;
private final int currentSoTimeout;
private long time = System.currentTimeMillis();
private int notAcked;

CSL(FTPClient parent, long idleTime, int maxWait) throws SocketException {
this.idle = idleTime;
this.parent = parent;
this.currentSoTimeout = parent.getSoTimeout();
parent.setSoTimeout(maxWait);
}

public void bytesTransferred(CopyStreamEvent event) {
this.bytesTransferred(event.getTotalBytesTransferred(), event.getBytesTransferred(), event.getStreamSize());
}

@Override
public void bytesTransferred(long l, int i, long l1) {
long now = System.currentTimeMillis();
if (now - this.time > this.idle) {
try {
this.parent.__noop();
} catch (SocketTimeoutException var9) {
++this.notAcked;
} catch (IOException e) {
logger.info("bytesTransferred Exception"+e);
}

this.time = now;
}
}

void cleanUp() throws IOException {
try {
while (this.notAcked-- > 0) {
this.parent.__getReplyNoReport();
}
} finally {
this.parent.setSoTimeout(this.currentSoTimeout);
}

}

}
}

FTPClient工具类的更多相关文章

  1. FTPClient 工具类

    package com.photoann.core.util; import java.io.BufferedInputStream; import java.io.File; import java ...

  2. FTP工具类开发

    正所谓工欲善其事必先利其器,熟悉了下一套流程,以此铭记. 1.FTP服务搭建 由于本人使用wondiow系统,所以针对window的童鞋们可以查看.至于windowX这里配置类似,所以不要纠结于win ...

  3. FTP上传-封装工具类

    import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...

  4. java中常用的工具类(二)

    下面继续分享java中常用的一些工具类,希望给大家带来帮助! 1.FtpUtil           Java   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...

  5. 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)

    前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上 ...

  6. ftp上传或下载文件工具类

    FtpTransferUtil.java工具类,向ftp上传或下载文件: package utils; import java.io.File; import java.io.FileOutputSt ...

  7. Java操作FTP工具类(实例详解)

    这里使用Apache的FTP jar 包 没有使用Java自带的FTPjar包  工具类 package com.zit.ftp; import java.io.File; import java.i ...

  8. ftp上传下载工具类

    package com.taotao.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNo ...

  9. FTPUtil工具类

    package com.xxx.common.util; import java.io.File; import java.io.FileOutputStream; import java.io.IO ...

随机推荐

  1. IIS 网站 HTTP 转 HTTPS

    最近需要做 http 链接转成 https 链接,所以就去弄了,现在记录下: 1.准备SSL证书 最开始的时候用的是腾讯云的免费证书,有效期1年,但只能绑定一个二级域名.测试成功后,就去阿里云购买了证 ...

  2. 阿里云配置gitlab邮箱

    gitlab_rails['gitlab_email_from'] = 'username@163.com' user['git_user_email'] = "username@163.c ...

  3. mysql时间日期操作

    SELECT uid, SUBSTR(addtime,1,10) as 创建日期, endtime, TIMESTAMPDIFF(MINUTE, addtime, endtime) as 直播时长 f ...

  4. 关于VC预定义常量_WIN32,WIN32,_WIN64

    VC2012 下写 Windows 程序时,有时需要判断编译环境.在之前的文章<判断程序是否运行在 Windows x64 系统下.>里说过如何在运行期间判断系统环境,但在编译时如何判断? ...

  5. Linux使用curl 方式安装docker-compose 后执行docker-compose version 检查安装是否成功时出错的解决办法

    0x0.缘起: 今天在一台新的Fedora 25上按照官方文档,使用curl方式安装 docker-compose后,验证是否安装成功时出错: 安装时使用的命令为; curl -L https://g ...

  6. 【OpenFOAM案例】02 自己动手

    前言:很多人说OpenFOAM很难,要啃上很多的理论书籍,什么流体力学.计算流体力学.矩阵理论.线性代数.数值计算.C++程序设计神马的,看看光这一堆书就能吓倒绝大多数的人.其实我们并不一定要从这些基 ...

  7. .NET Core +NuGet 创建打包发布自己的类库包

    1. 创建类库项目 你可以使用现有的 .NET 类库项目用于要打包的代码,或者创建一个简单的项目,.NET CORE 2.1 项目的 类库如下所示: NugetDemo.class using Sys ...

  8. AOSP中的HLS协议解析

    [时间:2018-04] [状态:Open] [关键词:流媒体,stream,HLS, AOSP, 源码分析,HttpLiveSource, LiveSession,PlaylistFetcher] ...

  9. mybatis 映射器(mappers) 配置说明 加载映射文件方式

    映射器(mappers) 既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要定义 SQL 映射语句了.但是首先我们需要告诉 MyBatis 到哪里去找到这些语句. Java 在自动查找这 ...

  10. 【转】导致SQL执行慢的原因

    索引对大数据的查询速度的提升是非常大的,Explain可以帮你分析SQL语句是否用到相关索引. 索引类似大学图书馆建书目索引,可以提高数据检索的效率,降低数据库的IO成本.MySQL在300万条记录左 ...