⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ftpcommander.java

📁 FTPCommand是一个在嵌入式环境(WindowsCE
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
                    throw new Exception(
                            "O arquivo eh maior do que a memoria livre " + size
                                    + " bytes <<.");
                }
                byte buff[] = new byte[1024]; // 8
                try {
                    addLog("Preparando para baixar " + size + " bytes" + "|");
                    lab1: for (lidos = 0; lidos < size;) {
                        if (interromper == 1)
                            throw new Exception("Interrompido pelo Usuario");
                        if (chunckSize > 64000) {
                            fila.enfileirar(tempBuffer);
                            tempBuffer = new BufferStream();
                            chunckSize = 0;
                        }
                        try {
                            tries = 0;
                            do {
                                count = tmp_socket.readBytes(buff, 0,
                                        buff.length);
                                if (count > 0)
                                    if (tempBuffer.writeBytes(buff, 0, count) < 0)
                                        throw new Exception(
                                                "Erro gravando temporario ! com "
                                                        + lidos);
                            } while (tries++ < 20
                                    && (tmp_socket.lastError == 4626 || tmp_socket.lastError == 6));
                            if (count <= 0) {
                                addLog(" erro nivel 2 - recebendo o arquivo "
                                        + tmp_socket.lastError);
                                addLog(" com " + lidos);
                                addLog(" bytes lidos | com " + tries);
                                addLog(" tentativas |");
                                throw new Exception(" erro nivel 2 -"
                                        + tmp_socket.lastError + " com "
                                        + lidos + " bytes lidos em " + tries
                                        + " tentativas - " + targetFileName);
                                // break lab1;
                            } //

                            lidos += count;
                            chunckSize += count;
                            concluido = lidos;
                        } catch (Exception e) {
                            throw new Exception(
                                    "erro nivel 1 - recebendo o arquivo "
                                            + targetFileName + " "
                                            + e.getMessage());
                        }
                    } // fim do loop
                    // ultimo objeto da fila
                    fila.enfileirar(tempBuffer);
                    addLog(targetFileName + lidos + " bytes recebidos" + "|");
                } catch (Exception e) {
                    throw new Exception("erro " + " preparando para baixar - "
                            + size + " bytes " + e.getMessage());
                }

                addLog("Resp .: " + readConsole(socketCom) + "|");
                //   fechando o socket !!!
                if (!Settings.onDevice) {
                    boolean fechou = tmp_socket.close();
                    addLog(!fechou ? "Nao consegui fechar o socket|"
                            + tmp_socket.lastError : "fechei o socket|");
                }
            }
        } catch (Exception e) {
            addLog(e.getMessage());
            addLog("|");
            throw new Exception(e.getMessage());
        }

        addLog("Resp .: " + readConsole(socketCom) + "|");
        return fila;
    }

    /**
     * @param lidos
     */

    public void setBin() throws Exception {
        fType = "type I";
        ftpCommand(fType, "", socketCom);
    }

    public boolean ftpPut(String targetFileName, byte[] buffer)
            throws Exception {
        int size = buffer.length;
        boolean sucesso = false;
        int count = 0;
        int tries = 0;
        String pv_line;
        try {
            addLog("Entrando em modo passivo | Put ");
            addLog(targetFileName);
            addLog("|");
            pv_line = (ftpCommand("pasv", "", socketCom));
            addLog(pv_line);
            int port = catchPort(pv_line);
            if (port < 1)
                throw new Exception("Porta Invalida " + port);

            tmp_socket = new Socket(url, port, timeout);
            try {
                addLog(ftpCommand("STOR ", targetFileName, socketCom));
            } catch (Exception e) {
                throw new Exception(" Falhou :" + e.getMessage());
            }
            addLog("|");
            int gravados = 0;
            tries = 0;
            int chunk = 256;
            try // 1
            {
                // no dispositivo a escrita eh interrompida
                // essa linha mandava toda a string para os sockets
                // resolvi dividir a tarefa em fatias de bytes (chunk)
                // count = tmp_socket.writeBytes(bb, 0, bb.length);

                for (int i = 0; i < size;) {
                    if (interromper == 1)
                        throw new Exception("Interrompido pelo Usuario");
                    if (!tmp_socket.isOpen())
                        throw new Exception("Socket auxiliar desconectou !!!");
                    int fi = ((i + chunk > size) ? (size - i) : chunk);
                    int wb;
                    do {
                        wb = tmp_socket.writeBytes(buffer, i, fi);
                        if (tmp_socket.lastError == 4626) {
                            addLog("erro de escrita , " + tmp_socket.lastError
                                    + " repetindo ... " + tries);
                        }

                        if (wb == -1)
                            addLog("erro de escrita , " + tmp_socket.lastError
                                    + " repetindo ... " + tries);
                    } while (tries++ < 20
                            && ((wb == -1) || ((tmp_socket.lastError == 4626 || tmp_socket.lastError == 6))));
                    if (wb != -1)
                        count += wb;
                    else {
                        //                        addLog("A conexao parece ter caido ! ..."
                        //                                + tmp_socket.lastError);
                        //                        addLog("|");
                        throw new Exception("A conexao parece ter caido ! ..."
                                + tmp_socket.lastError);
                        // break;
                    }
                    i += chunk;
                }
                if (count <= 0) {
                    sucesso = false;
                    addLog("erro enviando pedidos ..." + count + " bytes ");
                    addLog("|");
                }

                gravados += count;
                sucesso = (gravados == size);

            } catch (Exception e) {
                sucesso = false;
                throw new Exception("erro no nivel 1 - enviando pedidos|"
                        + e.getMessage());
                // e.printStackTrace();

            }
            if (true || !Settings.onDevice) {
                boolean fechou = tmp_socket.close();
                addLog(!fechou ? "Nao consegui fechar o socket "
                        : "fechei o socket ");
            }
            addLog("|");
            pv_line = readConsole(socketCom);
            ftpLastReturnCode = parseReturnCode(pv_line);
            addLog("Resp...: " + pv_line + "|");
            //            } // do (!(catch_port(pv_line) == 0))
            //            else {
            //                addLog("erro # " + socketCom.lastError + " - porta invalida "
            //                        + port + "|");
            //                sucesso = false;
            //             }
        } catch (Exception e1) {
            throw new Exception(e1.getMessage());
        }
        return sucesso;
    }

    public boolean sendNOOP() throws Exception {

        try {
            ftpCommand("NOOP ", "", socketCom);
        } catch (Exception e) {
            throw new Exception(" NOOP " + e.getMessage());
        }
        return true;
    }

    private String ftpCommand(String commandString, String ftp_arg, Socket sc)
            throws Exception {
        byte[] bytes = (commandString + ftp_arg.trim() + "\n").getBytes();
        int escrito = -1;
        int tryes = 0;
        do {
            escrito = sc.writeBytes(bytes, 0, bytes.length);
        } while (tryes++ < 10 && ((sc.lastError == 4626 || sc.lastError == 6)));
        if (escrito == -1)
            throw new Exception("Impossivel enviar comando ... "
                    + commandString + ftp_arg.trim() + " erro " + sc.lastError);
        ftpLastReturnCode = -1;
        String stringRetorno = "";
        try {
            stringRetorno = readConsole(sc);
        } catch (Exception e) {
            throw new Exception("erro no comando " + commandString
                    + ftp_arg.trim());
        }
        if (stringRetorno != "") {
            ftpLastReturnCode = parseReturnCode(stringRetorno);
        }
        return stringRetorno;
    }

    private int parseReturnCode(String st) {
        if (st.length() > 3)
            return Convert.toInt(st.substring(0, 3));
        else
            return ftpLastReturnCode;
    }

    /**
     * @param sc
     * @return
     * @throws Exception
     */
    private String readConsole(Socket sc) throws Exception {
        String stringRetorno = "";
        byte buf[] = new byte[512];
        int count = 0;
        int tries = 0;
        try {
            if (!sc.isOpen())
                throw new Exception("Socket desconectado - Status "
                        + sc.lastError);
            do {
                try {
                    count = sc.readBytes(buf, 0, buf.length);
                } catch (RuntimeException e1) {
                    throw new Exception("Socket desconectado - Status "
                            + sc.lastError + e1.getMessage());
                }
                if (count > 0) {
                    stringRetorno += new String(buf, 0, count);
                    break;
                }
            } while (tries++ < 20
                    && (count < 0 || (socketCom.lastError == 4626 || socketCom.lastError == 6)));
            if (stringRetorno.equals("") && (tries > 15)) {
                addLog("Tentando ler " + tries);
                addLog(".| ");
            }
        } catch (Exception e) {
            throw new Exception(" Nao Consegui ler : " + e.getMessage());
        }
        return stringRetorno;
    }

    private boolean abreFtpHost() throws Exception {
        boolean ab = false;
        int tryes = 0;
        int ConecTimeout = 1500;
        do {
            if (tryes > 10)
                ConecTimeout = 3000;
            try {
                socketCom = new Socket(url, porta, ConecTimeout, true);
                ab = socketCom.isOpen();
            } catch (Exception e) {
                socketCom = null;
                throw new Exception("Nao Consegui abrir conex鉶 com : " + url
                        + " " + e.getMessage());
            }

        } while (!ab && (tryes++ < numTentativasLogin));
        if (!ab)
            throw new Exception(" Login falhou apos " + tryes + " tentativas ");
        addLog("Conectado ap髎 " + (tryes + 1) + " tentativas ...|");
        return ab;
    }

    public boolean desconecta() {
        try {
            ftpCommand("QUIT", "", socketCom);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (socketCom.close())
            return Socket.disconnect();
        return false;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public int getPorta() {
        return porta;
    }

    public String getUrl() {
        return url;
    }

    public String getUsuario() {
        return usuario;
    }

    public void setTries(int numTentativas) {
        this.numTentativasLogin = numTentativas;
    }

    public StringBuffer getSb() {
        return sblogConexao;
    }

    public int getFtpLastReturnCode() {
        return ftpLastReturnCode;
    }

    public void setVerbose(boolean verbose) {
        this.verbose = verbose;
    }

    public void setInterromper() {
        FTPCommander.interromper = 1;
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -