📄 ftpcommander.java
字号:
/*
* Goldensoft Inform醫ica Ltda. www.goldensoft.inf.br
* suporte@goldensoft.inf.br
* Sivonei Neneve : sivuca@goldensoft.inf.br
* Licensa: GPL
*
* Esta classe utiliza o mesmo conceito de FTPtest com
* algumas melhorias entre elas:
*
* Melhor performance.
* Melhor manejo dos dados transferidos.
* Utiliza玢o de filas para permitir a transferencia de arquivos grandes (~64K).
* Simplifica玢o da logica.
*
* ============================= Created on 22/08/2006
*
*/
package util;
import superwaba.ext.xplat.io.BufferStream;
import waba.io.Socket;
import waba.sys.Convert;
import waba.sys.Settings;
import waba.sys.Vm;
public class FTPCommander {
private String usuario;
// private String senha;
private String url;
private int porta = 21;
private int timeout = 1500;
private Socket socketCom;
private Socket tmp_socket;
private int numTentativasLogin = 20;
private StringBuffer sblogConexao;
private int ftpLastReturnCode;
String dirRemoto = ".";
private String fType;
private int maximunStreamSize = Vm.getDeviceFreeMemory();
private boolean verbose = false;
private Fila fila;
private static int interromper = 0;
private int start;
private int end;
public int concluido;
public int currentBufferSize;
public boolean login(String url, int porta, String usuario, String senha,
String dirRemoto) throws Exception {
boolean sucesso = false;
this.usuario = usuario;
if (porta > 0)
this.porta = porta;
this.url = url;
this.sblogConexao = new StringBuffer("... inicio do log ...|");
this.start = Vm.getTimeStamp();
try {
// if (!abreFtpHost())
sucesso = abreFtpHost();
} catch (Exception e) {
sucesso = false;
throw new Exception("impossivel conectar " + e.getMessage());
}
this.socketCom.setReadTimeout(this.timeout);
try {
addLog(readConsole(this.socketCom));
String logCon = "USER " + usuario + "\n" + "PASS " + senha;
addLog(ftpCommand(logCon, "", this.socketCom));
addLog(readConsole(socketCom));
if ((null != dirRemoto) || ("".equals(dirRemoto)))
cmdCWD(dirRemoto);
} catch (Exception e) {
sucesso = false;
throw new Exception("impossivel conectar " + e.getMessage());
}
return sucesso;
}
/**
* @param dirRemoto
* @throws Exception
*/
public void cmdCWD(String dirRemoto) throws Exception {
addLog(ftpCommand("CWD ", dirRemoto, socketCom));
addLog("|");
}
/**
* @throws Exception
*/
public void cmdPWD() throws Exception {
addLog(ftpCommand("PWD ", "", socketCom));
addLog("|");
}
/**
*
*/
private void addLog(String string) {
if (verbose) {
if (false) {
end = Vm.getTimeStamp();
sblogConexao.append("|");
sblogConexao.append("milis.: "
+ funcoes.elapsedTimeSt(start, end));
sblogConexao.append("|");
start = Vm.getTimeStamp();
}
sblogConexao.append(string);
}
}
public boolean isOnline() {
return socketCom.isOpen();
}
public StringBuffer getrDirList() throws Exception {
String pv_line;
StringBuffer lista = new StringBuffer();
pv_line = (ftpCommand("pasv", "", socketCom));
int port = catchPort(pv_line);
if (port < 0)
throw new Exception("sem resposta do servidor para port :"
+ pv_line);
else
try {
tmp_socket = new Socket(url, port, timeout);
pv_line = (ftpCommand("list", "", socketCom));
addLog(pv_line);
addLog("|");
lista.append(readConsole(tmp_socket));
addLog((!tmp_socket.close()) ? "Nao consegui fechar o socket"
: "fechei o socket");
addLog("|");
// } else throw new Exception("sem resposta para port :" +
// pv_line);
} catch (Exception e) {
throw new Exception(e.getMessage());
}
addLog("Resp .: " + readConsole(socketCom) + "|");
return lista;
}
public StringBuffer getrNameList() throws Exception {
String pv_line;
StringBuffer lista = new StringBuffer();
pv_line = (ftpCommand("pasv", "", socketCom));
int port = catchPort(pv_line);
if (port > 0) {
try {
tmp_socket = new Socket(url, port, timeout);
pv_line = (ftpCommand("nlst", "", socketCom));
addLog(pv_line);
addLog("|");
// recebe
lista.append(readConsole(tmp_socket));
addLog((!tmp_socket.close()) ? "Nao consegui fechar o socket"
: "fechei o socket");
} catch (Exception e) {
throw new Exception("sem resposta : " + e.getMessage());
}
} else
throw new Exception("sem resposta para port :" + pv_line);
pv_line = readConsole(socketCom);
addLog("Resp .: " + pv_line + "|");
return lista;
}
/**
* @throws Exception
*
*/
public boolean fileExists(String compNome) throws Exception {
String pv_line;
String lista = "";
pv_line = (ftpCommand("pasv", "", socketCom));
int port = catchPort(pv_line);
try {
if (port > 0) {
tmp_socket = new Socket(url, port, timeout);
pv_line = (ftpCommand("nlst", "", socketCom));
addLog(pv_line);
addLog("|");
// recebe
lista = readConsole(tmp_socket);
addLog((!tmp_socket.close()) ? "Nao consegui fechar o socket"
: "fechei o socket");
} else
throw new Exception("sem resposta para port :" + pv_line);
} catch (Exception e) {
throw new Exception("sem resposta " + e.getMessage());
}
return (lista.indexOf(compNome) > 0);
}
private int catchPort(String pv_tbyt) {
int tmp_port = 0;
if (pv_tbyt.length() <= 0)
return tmp_port;
String pvs[] = Convert.tokenizeString(pv_tbyt, '(');
if (pvs.length < 2)
return tmp_port;
try {
String p1[] = Convert.tokenizeString(pvs[1], ')');
String p2[] = Convert.tokenizeString(p1[0], ',');
int tp1 = (Convert.toInt(p2[4].trim()));
int tp2 = (Convert.toInt(p2[5].trim()));
// peguei esse calculo na RFC do ftp !
tmp_port = ((tp1 * 256) + tp2);
return tmp_port;
} catch (Exception e) {
return tmp_port;
}
}
private int catchBytes(String pv_tbyt) {
String pvs[] = Convert.tokenizeString(pv_tbyt, '(');
if (pvs.length < 2)
return -1; // 0
String pvs1[] = Convert.tokenizeString(pvs[1], ' ');
if (pvs.length < 1)
return -2; // 0
int p_bytes = Convert.toInt(pvs1[0]);
return p_bytes;
}
public BufferStream ftpGetBS(String targetFileName) throws Exception {
BufferStream tempBuffer = null;
currentBufferSize = 0;
addLog("entrando em modo passivo ...| get ");
addLog(targetFileName);
addLog("|");
String pv_line;
try {
if (!socketCom.isOpen())
throw new Exception("Socket principal caiu "
+ socketCom.lastError);
pv_line = (ftpCommand("pasv", "", socketCom));
addLog(pv_line);
addLog("|");
int port = catchPort(pv_line);
if (port > 0) {
tmp_socket = new Socket(url, port, timeout);
if (!tmp_socket.isOpen())
throw new Exception("Impossivel abrir o socket - erro "
+ tmp_socket.lastError);
addLog("abrindo porta " + porta + "|");
addLog("enviando RETR " + targetFileName.trim() + "|");
String pv_tbyte = ftpCommand("RETR ", targetFileName.trim(),
socketCom);
addLog(pv_tbyte + "Calculando tamanho ");
currentBufferSize = catchBytes(pv_tbyte);
if (currentBufferSize <= 0)
throw new Exception(
"nao foi possivel estimar o tamanho do Arquivo "
+ targetFileName);
if (currentBufferSize > maximunStreamSize) {
throw new Exception(
"O arquivo eh maior do que a memoria livre "
+ currentBufferSize + " bytes <<");
}
tempBuffer = new BufferStream(tmp_socket);
}
} catch (Exception e) {
addLog(e.getMessage());
addLog("|");
}
return tempBuffer;
}
public Fila ftpGet(String targetFileName) throws Exception {
fila = new Fila();
int tries = 0;
int count = 0;
int size = 0;
int chunckSize = 0;
BufferStream tempBuffer = new BufferStream();
addLog("entrando em modo passivo ...| get ");
addLog(targetFileName);
addLog("|");
String pasvResponse;
try {
pasvResponse = (ftpCommand("pasv", "", socketCom));
addLog(pasvResponse);
addLog("|");
int port = catchPort(pasvResponse);
if (port < 0) {
throw new Exception(targetFileName
+ " - sem resposta do servidor para port :"
+ pasvResponse);
} else {
try {
tmp_socket = new Socket(url, port, timeout);
} catch (Exception e) {
throw new Exception("Impossivel abrir o socket - erro "
+ e.getMessage());
}
if (!tmp_socket.isOpen())
throw new Exception("Impossivel abrir o socket - erro "
+ tmp_socket.lastError);
addLog("abrindo porta " + porta + "|");
addLog("enviando RETR " + targetFileName.trim() + "|");
String pv_tbyte = ftpCommand("RETR ", targetFileName.trim(),
socketCom);
addLog(pv_tbyte + "Calculando tamanho ");
size = catchBytes(pv_tbyte);
currentBufferSize = size;
if (size <= 0)
throw new Exception(
"nao foi possivel estimar o tamanho do Arquivo "
+ targetFileName);
int lidos = 0;
if (size > maximunStreamSize) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -