com.gitee.apanlh.util.net.ftp.FtpDirectoryPath Maven / Gradle / Ivy
package com.gitee.apanlh.util.net.ftp;
import com.gitee.apanlh.exp.FtpPathException;
import com.gitee.apanlh.util.base.Empty;
import com.gitee.apanlh.util.valid.ValidParam;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilters;
/**
* FTP工作目录空间
*
* @author Pan
*/
class FtpDirectoryPath implements FtpCommandDirectoryPath {
private FtpCommandExecutor commandExecutor;
/** 目录文件对象 */
private FtpCommandDirectoryFile directoryFile;
/** 执行器 */
private FTPClient executor;
/** FTP命令 */
private FtpCommand command;
/** 当前工作目录 */
private String currentPath;
/** 当前工作所有目录 */
private String[] currentPaths;
/**
* 构造函数-默认
* @author Pan
*/
FtpDirectoryPath() {}
/**
* 构造函数-获取执行器
*
* @author Pan
* @param commandExecutors 命令执行器
*/
public FtpDirectoryPath(FtpCommandExecutor commandExecutors) {
this.commandExecutor = commandExecutors;
this.executor = commandExecutors.getExecutor();
this.command = commandExecutors.getCommand();
}
@Override
public boolean changeWorkingDirectory(String targetDir) {
try {
executor.changeWorkingDirectory(targetDir);
boolean completion = command.isCompletion(true);
if (completion) {
this.currentPath = targetDir;
}
return completion;
} catch (Exception e) {
throw new FtpPathException(e.getMessage(), e);
}
}
@Override
public String getCurrentPath() {
return this.currentPath;
}
@Override
public String[] getCurrentPaths() {
return this.currentPaths;
}
@Override
public String getDirectoryPath() {
char rangeStr = '\'';
String pwd = command.doCommandAsStringJoin("pwd", null);
if (!ValidParam.isEmpty(pwd)) {
this.currentPath = pwd.substring(pwd.indexOf(rangeStr) + 1, pwd.lastIndexOf(rangeStr));
}
return this.currentPath;
}
@Override
public String[] getDirectoryPathAll() {
FTPFile[] listDirectories = directoryFile.getFiles(this.currentPath, FTPFileFilters.DIRECTORIES);
boolean completion = command.isCompletion(true);
if (!completion) {
throw new FtpPathException(command.getCommandDetails());
}
if (listDirectories == null || listDirectories.length == 0) {
return Empty.arrayString();
}
// 获取当前目录下所有的工作空间
String[] worksPath = new String[listDirectories.length];
for (int i = 0, len = listDirectories.length; i < len; i++) {
worksPath[i] = listDirectories[i].getName();
}
this.currentPaths = worksPath;
return this.currentPaths;
}
@Override
public void beforeConfigure() {
this.directoryFile = commandExecutor.getDirectory().getDirectoryFile();
}
@Override
public void afterConfigure() {
// 获取当前工作空间
if (this.getCurrentPath() == null) {
getDirectoryPath();
}
}
}